<template>
  <div class="wrap">
    <div class="footer" v-if="currentWorkType !== ''">
      <el-button @click="cancelOp">{{ $t('common.cancel') }}</el-button>
      <template v-if="currentWorkType === workTypeMap.picking">
        <el-button type="primary" @click="finishBox" :disabled="boxIsEveryInstall" v-if="data.status === 'wait_make_cabinet'">确认已装柜</el-button>
      </template>
      <template v-if="currentWorkType === workTypeMap.return">
        <template v-if="returnOrder.orderId">
          <el-button type="primary" :loading="stockBtnLoading" @click="backStock">{{ $t('common.confirm') }}</el-button>
          <!--<el-button type="primary" :loading="confirmAndPrintTheNewBtnLoading" @click="confirmAndPrintTheNewLabel();backStock();" style="background-color: rgba(63, 86, 128, 1)">{{ $t('common.Confirm and print the new label') }}</el-button>-->
          <hardware-print-sku-info :data="returnOrder" :refundGoods="returnForm.refundGoods" @child-data="handleChildData"></hardware-print-sku-info>
        </template>
      </template>
      <template v-if="currentWorkType === workTypeMap.tallying">
        <template v-if="shipmentInfo.id && shipmentInfo.status === 0 && (!shipmentInfo.labelOrder || shipmentInfo.labelOrder.status === 2)">
          <el-button type="primary" @click="checkShipment" :loading="shipmentLoading">{{ $t('shipment.Confirm receipt') }}</el-button>
        </template>
      </template>
      <template v-if="currentWorkType === workTypeMap.transfer">
        <template v-if="transferMode === 3 && transferInfo.id && (!transferInfo.labelOrder || transferInfo.labelOrder.status === 2)">
          <el-button type="primary" @click="finishTransfer" v-if="transferInfo.status === 1" :loading="btnLoading">{{ $t('transfer.确认调货') }}</el-button>
        </template>
      </template>
      <template v-if="currentWorkType === workTypeMap.middle">
        <template v-if="middleInfo.status === 1 && (!middleInfo.labelOrder || middleInfo.labelOrder.status === 2) && middleMode === 3">
          <el-button type="primary" @click="pickedMiddle" :loading="btnLoading">{{ $t('middle.确认已拣货') }}</el-button>
        </template>
      </template>
      <template v-if="currentWorkType === workTypeMap.label">
        <template v-if="labelMode === 3">
          <el-button type="primary" @click="checkLabelGoodsNum" :loading="btnLoading">{{ $t('labelOrder.确认已贴标') }}</el-button>
        </template>
      </template>
    </div>
    <div class="header">
      <div class="header-title">
        {{ getDomainName() }} {{ $t('hd.Hardware Mode') }}
        <span class="font-red mgr10" v-if="currentWorkType !== ''">- {{ workTypeName }}</span>
        <el-button :type="canCloseAppDialog ? 'success' : 'danger'" :icon="canCloseAppDialog ? 'el-icon-success' : 'el-icon-error'" @click="appStartDialog = true">
          {{ $t('hd.hardware status') }}
        </el-button>

        <el-button @click="startApp" v-if="!appCheckStatus.appStart">{{ $t('hd.start app') }}</el-button>

        <!-- <el-button @click="resetWorkType">{{ $t('hd.Switch Mode') }}</el-button> -->

        <div style="width: 300px" v-if="false">
          <el-input v-model="selfKeyword"></el-input>
          <el-button @click="searchBySelf">{{ $t('common.search') }}</el-button>
        </div>
      </div>
      <div class="mgt20" v-if="isTesting() && currentWorkType !== ''">
        演示模式专用：
        <template v-if="currentWorkType === workTypeMap.tallying">
          <el-button type="primary" class="mgb10" @click="scannerInput('X003J4SN13')">扫描单货件场景-SKU：X003J4SN13</el-button>
          <el-button type="primary" class="mgb10" @click="scannerInput('02_style1_M')">扫描多货件场景-SKU：02_style1_M</el-button>
          <el-button type="primary" class="mgb10" @click="scannerInput('v1-1166-5518-6934-0')">扫描箱标-v1-1166-5518-6934-0</el-button>
        </template>
        <template v-if="currentWorkType === workTypeMap.return">
          <el-button type="primary" class="mgb10" @click="scannerInput('42764095997')">扫描退货场景-单个商品-面单号:42764095997</el-button>
          <el-button type="primary" class="mgb10" @click="scannerInput('42615241259')">扫描退货场景-多个商品-面单号:42615241259</el-button>
          <el-button type="primary" class="mgb10" @click="scannerInput('22615241259')">扫描退货场景-无对应订单场景-面单号:22615241259</el-button>
        </template>
        <template v-if="currentWorkType === workTypeMap.picking">
          <el-button type="primary" class="mgb10" @click="getTestingSku(1)" :loading="testingSkuLoading">扫描SKU标-单商品单数量订单</el-button>
          <el-button type="primary" class="mgb10" @click="getTestingSku(2)" :loading="testingSkuLoading">扫描SKU标-单商品多数量订单</el-button>
          <el-button type="primary" class="mgb10" @click="getTestingSku(3)" :loading="testingSkuLoading">扫描SKU标-多商品订单</el-button>
          <el-button type="primary" class="mgb10" @click="scannerInput('X003WKI4B3')" :loading="testingSkuLoading">扫描SKU标-无对应订单-SKU:X003WKI4B3</el-button>
          <el-button type="primary" class="mgb10" @click="scannerInput('42765816274')">扫描面单-单商品场景-面单号:42765816274</el-button>
          <el-button type="primary" class="mgb10" @click="scannerInput('42766736386')">扫描面单-多商品场景-面单号:42766736386</el-button>
          <el-button type="primary" class="mgb10" @click="scannerInput('42543027397')">扫描面单-订单取消场景-面单号:42543027397</el-button>
          <el-button type="primary" class="mgb10" @click="scannerInput('41923188115')">扫描面单-订单退货场景-面单号:41923188115</el-button>
        </template>
        <template v-if="currentWorkType === workTypeMap.transfer">
          <el-button type="primary" class="mgb10" @click="scannerInput('X003TYQRT3')">扫描SKU：X003TYQRT3</el-button>
        </template>
        <template v-if="currentWorkType === workTypeMap.middle">
          <el-button type="primary" class="mgb10" @click="scannerInput('X003KPHINP')">扫描SKU：X003KPHINP</el-button>
        </template>
      </div>
      <div class="mgt20" v-if="isTesting() && currentWorkType !== ''">
        演示模式专用自定义扫描内容：
        <el-input v-model="selfKeyword" style="width: 200px" @keyup.enter.native="diyScan"></el-input>
        <el-button type="primary" @click="diyScan">模拟扫描</el-button>
      </div>
    </div>

    <div class="content">
      <div style="display: flex">
        <div class="header-tips">
          <div>
            {{ $t('hd.When using hardware such as scanning guns,') }}
          </div>
          <div>
            <!--            1. 请等待{{getDomainName()}}硬件APP「{{getMDName()}}」，等待设备连接完成-->
            {{ $t('hd.HDTipsText1', { domainName: getDomainName(), MDName: getMDName() }) }}
          </div>
          <div>
            {{ $t('hd.HDTipsText2') }}
          </div>
        </div>
        <div v-if="currentWorkType === workTypeMap.picking && pickingOrderType === 'goods'" class="picking-goods-tips">
          <div>{{ $t('hd.pickingText2') }}，</div>
          <div>{{ $t('hd.pickingText3') }}</div>
          <div class="font-red font-bold">{{ $t('hd.pickingText4') }}</div>
        </div>
      </div>

      <div class="mgt20" v-if="orderScannerType === 'nothing' || orderScannerType === ''">
        {{ $t('hd.HDTipsText3') }}
        <gun-model-set style="display: inline" @printPDF="printPDF" :gunScannerTest="gunScannerTest" @changeDialog="changeGunScannerTestValue"></gun-model-set>
      </div>
      <div class="mgt20" v-if="$store.getters.inventoryLocationNum <= 0 && mdType === 1">
        <span>{{ $t('table.inventoryLocation.您当前尚未创建库位，库位创建后可以更清晰明了的管理库存；') }}</span>
        <br />
        <span>{{ $t('table.inventoryLocation.未创建库位不影响入库，您也可以在入库后前往【库存管理】操作创建，马上创建请点击：') }}</span>
        <el-button type="primary" @click="jumpInventoryLocationList">{{ $t('table.inventoryLocation.创建库位') }}</el-button>
      </div>
      <div class="scanner-text" v-if="false">{{ $t('hd.Current scan results') }}: {{ scannerTest }}</div>
    </div>

    <!--  切换模式   -->
    <div class="content" v-if="currentWorkType === ''">
      <div class="font-bold font-red">{{ $t('hd.Please select the current working mode') }}</div>

      <div class="mode-box">
        <div class="font-bold mode-title">
          {{ $t('hd.Warehousing mode') }}
        </div>
        <div class="work-type-select">
          <div class="work-type-box" @click="selectWorkType(item)" v-for="item in workTypeList.filter((item) => item.md === 1)" :key="item.workType">
            <div class="work-type-card">
              <div class="title" :class="item.md === 1 ? 'font-blue' : 'font-red'">{{ item.modeName }}</div>
              <div class="work-img">
                <img :src="item.modeImage" alt="" />
              </div>
            </div>
            <div v-if="false" class="work-type-title" :class="item.md === 1 ? 'font-blue' : 'font-red'">{{ item.mode }}</div>
          </div>
        </div>
      </div>

      <div class="mode-box">
        <div class="font-bold mode-title">
          {{ $t('hd.Outbound mode') }}
        </div>
        <div class="work-type-select">
          <div class="work-type-box" @click="selectWorkType(item)" v-for="item in workTypeList.filter((item) => item.md === 2)" :key="item.workType">
            <div class="work-type-card">
              <div class="title" :class="item.md === 1 ? 'font-blue' : 'font-red'">{{ item.modeName }}</div>
              <div class="work-img">
                <img :src="item.modeImage" alt="" />
              </div>
            </div>
            <div v-if="false" class="work-type-title" :class="item.md === 1 ? 'font-blue' : 'font-red'">{{ item.mode }}</div>
          </div>
        </div>
      </div>
    </div>
    <div v-show="false">
      当前扫描结果：
      <scanner @onScannerInput="scannerInput" :show="false"></scanner>
    </div>

    <div class="work-content" v-if="currentWorkType !== ''" v-loading="dataLoading">
      <div class="work-return mgt20" v-if="currentWorkType === workTypeMap.return">
        <div class="tips-text">
          <span v-html="$t('hd.returnText1')"></span>
        </div>
        <template v-if="returnOrder.orderId">
          <div class="card-box">
            <el-card class="order-card-1 mgt20">
              <div class="order-header-title">{{ $t('hd.returnText2') }}</div>
              <div class="order-card">
                <el-descriptions title="" :column="2" colon labelClassName="order-card-label" contentClassName="order-card-text" size="medium" :labelStyle="{ width: '100px' }">
                  <el-descriptions-item :label="$t('hd.Current scan results')">
                    {{ scannerTest }}
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('table.orderId')">
                    {{ returnOrder.orderId }}
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('hd.Sticking status')">
                    {{ returnOrder.stickerStatus === 1 ? $t('hd.Posted') : $t('hd.Not labeled') }}
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('table.platform')">
                    <span :class="getPlatformTextColor(returnOrder.accountType)">{{ returnOrder.accountType }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('hd.Delivery method')">
                    <span :class="getLogisticTypeTextColor(returnOrder.logisticType)">{{ getOrderLogisticType(returnOrder.logisticType) }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('table.user name')">
                    {{ returnOrder.userAccount }}
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('hd.Status')">
                    <span class="font-red">
                      {{ returnOrder.statusStr }}
                    </span>
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('order.Shop Name')">
                    {{ returnOrder.showName }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </el-card>
            <el-card class="order-return-card mgt20 mgl20">
              <template v-if="returnOrder.toStock === -1">
                <div class="return-header-title">{{ $t('hd.Please choose whether to refund the current order fee') }}</div>
                <div class="return-header-text">{{ $t('hd.Total cost of labeling') }}：{{ returnOrder.stickerPrice || 0 }}</div>
                <div class="return-btn">
                  <el-button :type="returnForm.refundSticker === 0 ? 'primary' : ''" @click="returnForm.refundSticker = 0">
                    {{ $t('order.Do not return') }}
                  </el-button>
                  <el-button :type="returnForm.refundSticker === 1 ? 'primary' : ''" @click="returnForm.refundSticker = 1">
                    {{ $t('order.return') }}
                  </el-button>
                </div>

                <div style="font-size: 12px; color: #aeaeae" class="font-bold">
                  {{ $t('hd.returnText3') }}
                </div>
              </template>
              <template v-else>
                <div class="return-op-tips">该订单已进行过退货处理操作</div>
                <div class="mgt20 font-red font-bold">贴单金额：{{ returnOrder.toStock === 1 ? '已退回' : '不退回' }}</div>
              </template>
            </el-card>
          </div>
          <div class="return-order-list">
            <div class="font-red mgb10">
              {{ $t('hd.returnText4') }}
            </div>

            <template v-if="returnOrder.toStock !== -1">
              <div class="font-bold font-red mgb10" style="font-size: 24px">{{ $t('hd.returnText6') }}</div>
            </template>
            <div class="return-order-item" v-for="(subOrder, index) in returnOrder.subOrders" :key="subOrder.subOrderId">
              <div class="left">
                <el-image
                  style="width: 400px; cursor: pointer"
                  :src="goodsOriginImage(subOrder)[0] || subOrder.goodsImage"
                  :preview-src-list="goodsOriginImage(subOrder)"
                ></el-image>
              </div>
              <div class="right">
                <el-card class="goods-info-card">
                  <div class="goods-info-card-content">
                    <div class="goods-listing">
                      {{ subOrder.goodsId }} {{ $t('common.num') }}：
                      <span class="font-red">{{ subOrder.num }}</span>
                    </div>
                    <div class="goods-title">{{ subOrder.goodsTitle }}</div>
                    <div class="goods-SKU-info">SKU: {{ subOrder.sku || '-' }}</div>
                    <div class="goods-attr">
                      <span v-for="attr in subOrder.attributes" :key="attr.name" class="attr font-red">
                        {{ attr.name }} : {{ attr.value }}
                        <span class="attr-link">|</span>
                      </span>
                    </div>
                    <div class="return-input">
                      {{ $t('hd.Quantity of goods to be restocked') }}：
                      <el-input-number :max="subOrder.num" :min="0" :step="1" :precision="0" v-model="returnForm.refundGoods[index].num"></el-input-number>
                      <span class="font-red mgl20">{{ $t('hd.returnText5') }}</span>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </div>
        </template>
      </div>

      <div class="work-tallying mgt20" v-if="currentWorkType === workTypeMap.tallying">
        <div class="tips-text" v-if="tallyingMode === 1">
          <span v-html="$t('hd.请使用扫码枪扫描货件中的一个SKU标或箱标以继续')"></span>
        </div>
        <div v-if="tallyingMode === 2">
          <div class="tips-text">
            <span>{{ $t('hd.TallyingText2') }}</span>
          </div>
          <div class="shipmentList-table">
            <el-table :data="shipmentList" border style="width: 1050px">
              <el-table-column :label="$t('table.shipmentNumber')" prop="shipmentNo" align="center" min-width="200" show-overflow-tooltip>
                <template slot-scope="{ row }">
                  <diy-link @click="getShipmentInfo(row.id)">{{ row.shipmentNo }}</diy-link>
                </template>
              </el-table-column>

              <el-table-column :label="$t('table.warehouse')" prop="typeStr" align="center" width="200"></el-table-column>

              <el-table-column :label="$t('table.Expected number of inbound boxes')" prop="exGoodsNum" align="center" width="200">
                <template slot-scope="{ row }">
                  <tool-tip-shipment-box :shipment-box="row.shipmentBox" type="EX"></tool-tip-shipment-box>
                </template>
              </el-table-column>

              <el-table-column :label="$t('table.Expected quantity of goods to be received')" prop="exGoodsNum" align="center" width="200"></el-table-column>
              <el-table-column :label="$t('table.贴标状态')" prop="labelOrderStatus" align="center" width="200">
                <template v-slot="{ row }">
                  {{ row.labelOrder ? getLabelStatusStr(row.labelOrder.status) : $t('shipment.无需贴标') }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-if="tallyingMode === 3">
          <shipment-info-view
            :data="shipmentInfo"
            :shipment-goods="shipmentGoods"
            :shipment-box="shipmentBox"
            :h-w-mode="true"
            @changeData="changeShipmentData"
          ></shipment-info-view>

          <ShipmentInfoImg :data="shipmentInfo" :updateImgUrl="updateImgUrl" :saveFunc="saveShipmentImg" :getFunc="getShipmentImgArr"></ShipmentInfoImg>
        </div>
      </div>
      <!-- 出库模式 装柜 -->
      <div class="work-picking mgt20" v-if="currentWorkType === workTypeMap.picking">
        <div class="tips-text" v-if="pickingOrderType === ''">
          <span v-html="$t('hd.pickingText16')"></span>
        </div>
        <div class="work-picking-content" v-if="pickingOrderType !== ''">
          <container-info-view :data="containerData" @getData="getContainer(containerData.id)"></container-info-view>
        </div>
      </div>

      <div class="work-transfer mgt20" v-if="currentWorkType === workTypeMap.transfer">
        <div class="tips-text" v-if="transferMode === 1">
          <span v-html="$t('hd.transferText1')"></span>
        </div>
        <div v-if="transferMode === 2">
          <div class="tips-text">
            <span>{{ $t('hd.transferText2') }}</span>
          </div>
          <div class="transfer-table">
            <el-table :data="transferList" border style="width: 1100px">
              <el-table-column :label="$t('table.调货单号')" prop="workNo" align="center" min-width="200" show-overflow-tooltip>
                <template slot-scope="{ row }">
                  <template v-if="row.labelOrder && row.labelOrder.status !== 2">
                    <diy-link @click="isSwitchLabelModel(row.labelOrder.id)">{{ row.workNo }}</diy-link>
                  </template>
                  <template v-else>
                    <diy-link @click="getTransferInfo(row.id)">{{ row.workNo }}</diy-link>
                  </template>
                </template>
              </el-table-column>

              <el-table-column :label="$t('table.store')" prop="accountName" align="center" min-width="150"></el-table-column>

              <el-table-column :label="$t('table.调货SKU种数')" prop="exSkuNum" align="center" width="200"></el-table-column>
              <el-table-column :label="$t('table.调货商品总数')" prop="exGoodsNum" align="center" width="200"></el-table-column>

              <el-table-column :label="$t('table.调货类型')" prop="type" align="center" width="100">
                <template v-slot="{ row }">
                  {{ getTransferTypeStr(row.type) }}
                </template>
              </el-table-column>
              <el-table-column :label="$t('table.贴标状态')" prop="labelStatus" align="center" width="100">
                <template v-slot="{ row }">
                  {{ getMiddleLabelStatusStr(row) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-else-if="transferMode === 3">
          <transfer-info-view :distribution-goods-list="distributionGoodsList" :straight-goods="straightGoods" :data="transferInfo"></transfer-info-view>
        </div>
      </div>

      <div class="work-middle mgt20" v-if="currentWorkType === workTypeMap.middle">
        <div class="tips-text" v-if="middleMode === 1">
          <span v-html="$t('hd.transferText1')"></span>
        </div>
        <div v-if="middleMode === 2">
          <div class="tips-text">
            <span>{{ $t('hd.middleText1') }}</span>
          </div>
          <div class="middle-table">
            <el-table :data="middleList" border style="width: 1100px">
              <el-table-column :label="$t('middle.送仓工单')" prop="workNo" align="center" min-width="200" show-overflow-tooltip>
                <template slot-scope="{ row }">
                  <template v-if="row.labelOrder && row.labelOrder.status !== 2">
                    <diy-link @click="isSwitchLabelModel(row.labelOrder.id)">{{ row.workNo }}</diy-link>
                  </template>
                  <template v-else>
                    <diy-link @click="getMiddleInfo(row.id)">{{ row.workNo }}</diy-link>
                  </template>
                </template>
              </el-table-column>

              <el-table-column :label="$t('table.store')" prop="accountName" align="center" min-width="150"></el-table-column>

              <el-table-column :label="$t('table.送仓SKU种数')" prop="exSkuNum" align="center" width="200"></el-table-column>
              <el-table-column :label="$t('table.送仓商品总数量')" prop="exGoodsNum" align="center" width="200"></el-table-column>

              <el-table-column :label="$t('table.贴标状态')" prop="labelStatus" align="center" width="100">
                <template v-slot="{ row }">
                  {{ getMiddleLabelStatusStr(row) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-else-if="middleMode === 3">
          <middle-info-view :distribution-goods-list="middleDistributionGoodsList" :straight-goods="middleStraightGoods" :data="middleInfo"></middle-info-view>
        </div>
      </div>

      <div class="work-label mgt20" v-if="currentWorkType === workTypeMap.label">
        <div class="tips-text" v-if="labelMode === 1">
          <span v-html="$t('hd.transferText1')"></span>
        </div>
        <div v-if="labelMode === 2">
          <div class="tips-text">
            <span>{{ $t('hd.middleText1') }}</span>
          </div>
          <div class="label-table">
            <el-table :data="labelList" border style="width: 1100px">
              <el-table-column :label="$t('table.贴标单号')" prop="labelNo" align="center" min-width="200" show-overflow-tooltip>
                <template slot-scope="{ row }">
                  <diy-link @click="getLabelInfo(row.id)">{{ row.labelNo }}</diy-link>
                </template>
              </el-table-column>

              <el-table-column :label="$t('table.预计贴标SKU种数')" prop="exSkuNum" align="center" width="200"></el-table-column>
              <el-table-column :label="$t('table.预计贴标商品总数量')" prop="exGoodsNum" align="center" width="200"></el-table-column>

              <el-table-column :label="$t('table.贴标类型')" prop="type" align="center" width="100">
                <template v-slot="{ row }">
                  {{ getLabelTypeStr(row.type) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div v-if="labelMode === 3">
          <label-order-info-view :goods-data="labelGoodsData" :data="labelInfo"></label-order-info-view>
        </div>
      </div>
    </div>
    <el-dialog title="编辑失败箱唛" :visible.sync="editFailDialog">
      <div style="margin-top: -20px">
        <div class="not-found-box mgt10" v-if="notFoundBox.length > 0">
          <div>以下箱唛不存在系统中：</div>
          <div v-for="item in notFoundBox" :key="item" class="font-red">
            {{ item }}
          </div>
        </div>
        <div class="diff-box mgt10" v-if="diffTypeBox.length > 0">
          <div>以下箱唛运输类型不匹配不可添加：</div>
          <div v-for="item in diffTypeBox" :key="item" class="font-red">
            {{ item }}
          </div>
        </div>
        <div class="other-box mgt10" v-if="otherBox.length > 0">
          <div>以下箱唛已存在其他货柜中：</div>
          <div v-for="item in diffTypeBox" :key="item">
            {{ item }}
          </div>
        </div>
      </div>
      <template slot="footer">
        <el-button type="primary" v-if="otherBox.length > 0" @click="addOtherBox">将其它货柜箱唛添加到当前货柜</el-button>
        <el-button @click="editFailDialog = false">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="editDialog" width="600px" title="编辑货件">
      <div>
        <div style="margin-top: -20px">通过货件箱唛为当前货柜新增或移除货件</div>
        <el-form :form="dialogForm" label-width="100px">
          <el-form-item label="操作类型" prop="type">
            <el-radio-group v-model="dialogForm.type">
              <el-radio label="add">新增箱唛</el-radio>
              <el-radio label="remove">移除箱唛</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="货件箱唛" prop="boxIds">
            <el-input type="textarea" autosize placeholder="请输入" v-model="dialogForm.boxIds"></el-input>
            <div class="tips">换行输入多个箱唛可批量编辑</div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitDialogForm" :loading="digBtnLoading">确定</el-button>
            <el-button @click="editDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="appStartDialog"
      width="600px"
      :title="getMDName() + '-' + $t('hd.Start detection')"
      :close-on-click-modal="canCloseAppDialog"
      :close-on-press-escape="canCloseAppDialog"
      :show-close="canCloseAppDialog"
    >
      <div class="dialog-content">
        <div class="app-check-tips">
          <div>
            {{ $t('hd.checkText1', { domainName: getDomainName(), HDName: getMDName() }) }}
            <!--            1. 请等待{{getDomainName()}}硬件APP「{{getMDName()}}」完成设备连接-->
          </div>
          <div>
            {{ $t('hd.checkText2', { HDName: getMDName() }) }}
            <!--            2. 如果「{{getMDName()}}」未能自动打开，请手动开启-->
          </div>
        </div>
        <el-form label-width="150px" label-suffix=":" style="font-size: 16px">
          <el-form-item :label="$t('hd.Service Connection Status')" prop="account">
            <template v-if="appCheckStatus.appStart">
              <span class="success-color">
                {{ $t('hd.Successfully connected') }}
                <i class="el-icon-success"></i>
              </span>
            </template>
            <template v-else>
              <span class="wait-color">
                {{ $t('hd.Waiting to connect') }}
                <i class="el-icon-loading"></i>
              </span>
            </template>
          </el-form-item>
          <el-form-item :label="$t('hd.APP version')" prop="password">
            <template v-if="!appCheckStatus.appStart">
              <span class="wait-color">
                {{ $t('hd.Waiting to connect') }}
                <i class="el-icon-loading"></i>
              </span>
            </template>
            <template v-else-if="appCheckStatus.appVersion === appVersion">
              <span class="success-color">
                {{ $t('hd.Version matching successful') }}
                <i class="el-icon-success"></i>
              </span>
            </template>
            <template v-else>
              <!--              <span class="error-color">版本匹配错误，当前系统版本{{appVersion}},APP版本{{appCheckStatus.appVersion}}<i class="el-icon-error"></i></span>-->
              <span class="error-color">
                {{ $t('hd.Version matching error', { version1: appVersion, version2: appCheckStatus.appVersion }) }}
                <i class="el-icon-error"></i>
              </span>
            </template>
          </el-form-item>
          <el-form-item :label="$t('hd.system printer')">
            <template v-if="!appCheckStatus.appStart">
              <span class="wait-color">
                {{ $t('hd.Waiting to connect') }}
                <i class="el-icon-loading"></i>
              </span>
            </template>
            <template v-else-if="appCheckStatus.printersState">
              <span class="success-color">
                {{ $t('hd.Successfully obtained configuration') }}
                <i class="el-icon-success"></i>
              </span>
            </template>
            <template v-else>
              <span class="error-color">
                {{ $t('hd.Failed to obtain configuration') }}
                <i class="el-icon-error"></i>
              </span>
            </template>
          </el-form-item>
          <el-form-item :label="$t('hd.The currently selected printer')">
            <template v-if="!appCheckStatus.appStart">
              <span class="wait-color">
                {{ $t('hd.Waiting to connect') }}
                <i class="el-icon-loading"></i>
              </span>
            </template>
            <template v-else-if="appCheckStatus.printersState">
              <template v-if="printers.length === 0">
                <span class="error-color">
                  {{ $t('hd.The current system has not configured a printer') }}
                  <i class="el-icon-error"></i>
                </span>
              </template>
              <template v-else>
                <el-select v-model="currentPrinter" :placeholder="$t('hd.Please select a printer')" style="width: 300px" value-key="name" @change="testPrinter">
                  <el-option v-for="item in printers" :key="item.name" :label="`${item.description}(${item.displayName || item.description})`" :value="item"></el-option>
                </el-select>
              </template>
            </template>
            <template v-else>
              <span class="error-color">
                {{ $t('hd.Failed to obtain configuration') }}
                <i class="el-icon-error"></i>
              </span>
            </template>
          </el-form-item>
          <el-form-item :label="$t('hd.Electronic scale')">
            <template v-if="!appCheckStatus.appStart">
              <span class="wait-color">
                {{ $t('hd.Waiting to connect') }}
                <i class="el-icon-loading"></i>
              </span>
            </template>
            <template v-else-if="appCheckStatus.scalesState === scalesStateMap.search">
              <span class="wait-color">
                {{ $t('hd.Device search in progress') }}
                <i class="el-icon-loading"></i>
              </span>
            </template>
            <template v-else-if="appCheckStatus.scalesState === scalesStateMap.connected">
              <span class="wait-color">
                <template v-if="scaleDeviceInfo && scaleDeviceInfo.subType === 'virtual-serial-port'">
                  {{ $t('hd.Wireless in device preparation') }}
                </template>
                <template v-else>
                  {{ $t('hd.Device preparation wired') }}
                </template>
                <!--                设备准备中 {{ scaleDeviceInfo ? `(${scaleDeviceInfo.subType === 'virtual-serial-port' ? '无线' : '有线'})` : '' }} -->
                <i class="el-icon-loading"></i>
              </span>
            </template>
            <template v-else-if="appCheckStatus.scalesState === scalesStateMap.transform">
              <span class="success-color">
                <template v-if="scaleDeviceInfo && scaleDeviceInfo.subType === 'virtual-serial-port'">
                  {{ $t('hd.Device completed connecting wirelessly') }}
                </template>
                <template v-else>
                  {{ $t('hd.Device completed connecting wired') }}
                </template>
                <!--                设备完成连接 {{ scaleDeviceInfo ? `(${scaleDeviceInfo.subType === 'virtual-serial-port' ? '无线' : '有线'})` : '' }} -->
                <i class="el-icon-success"></i>
              </span>
            </template>
            <template v-else-if="appCheckStatus.scalesState === scalesStateMap.discontented">
              <span class="error-color">
                {{ $t('hd.Disconnect') }}
                <i class="el-icon-error"></i>
              </span>
            </template>
            <template v-else>
              <span class="error-color">
                {{ $t('hd.connection exception') }}
                <i class="el-icon-error"></i>
              </span>
            </template>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="gunDialog"
      width="800px"
      :title="gunStep <= 2 ? `${$t('hd.Set the scanning gun mode')}（${gunStep}/3）` : `${$t('hd.Test scanning gun')}（${gunStep}/3）`"
    >
      <div v-if="gunStep === 1">
        <div>
          <span v-html="$t('hd.Please use a barcode scanner to scan the barcode below,')"></span>
          <!--          请使用<span class="error-color" style="font-weight: bold">扫码枪</span>扫描下方条形码,-->
          <br />
          <span v-html="$t('hd.gunText1')"></span>
          <!--          并在扫码枪<span class="error-color" style="font-weight: bold">震动</span>或者听到<span class="error-color" style="font-weight: bold">“嘀”的一声</span>后，点击「下一步」按钮：-->
        </div>
        <div class="mgt20">
          <img src="~@/assets/images/scanner1.png" alt="" width="250" />
          <!--        <div>2.4G模式</div>-->
          <div>{{ $t('hd.Setting code 1') }}</div>
        </div>
        <div class="gun-model-tips mgt20">
          {{ $t('hd.gunText2') }}
          <br />
          {{ $t('hd.gunText3') }}
        </div>
      </div>
      <div v-if="gunStep === 2">
        <div>
          <span v-html="$t('hd.Please use a barcode scanner to scan the barcode below,')"></span>
          <br />
          <span v-html="$t('hd.gunText1')"></span>
        </div>
        <div style="margin-top: 20px">
          <img src="~@/assets/images/scanner2.png" alt="" width="250" />
          <!--          <div>美国键盘</div>-->
          <div>{{ $t('hd.Setting code 2') }}</div>
        </div>
        <div class="gun-model-tips mgt20">
          {{ $t('hd.gunText2') }}
          <br />
          {{ $t('hd.gunText3') }}
        </div>
      </div>
      <div v-if="gunStep === 3">
        <div class="gun-model-tips">
          {{ $t('hd.gunText4') }}
          <br />
          - {{ $t('hd.gunText5') }}
          <br />
          - {{ $t('hd.gunText6') }}
        </div>
        <div>
          <svg id="barcode"></svg>
        </div>
        <div class="mgt10">{{ $t('hd.Barcode content') }}：{{ gunTestStr }}</div>
        <div class="mgt10">
          {{ $t('hd.Current Scan Content') }}：
          <el-input style="display: inline-block; width: 300px" ref="testInput" :value="gunScannerTest"></el-input>
        </div>
        <div class="mgt20">
          <el-button type="danger" @click="gunStep = 1">{{ $t('hd.Rematch') }}</el-button>
          <el-button @click="printGunTest" :disabled="!currentPrinter" :loading="printerTestLoading">{{ $t('hd.Print setup code') }}</el-button>
        </div>
      </div>

      <div slot="footer" class="dialog-footer" v-if="gunStep <= 2">
        <el-button @click="printGunTest" :disabled="!currentPrinter" :loading="printerTestLoading">{{ $t('hd.Print setup code') }}</el-button>
        <el-button type="warning" @click="gunStep++">{{ $t('common.next') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="goodsNumOverDialog1" :title="$t('hd.实际数量已超过预计数量')" width="400px">
      <div style="margin-top: -20px">
        <div class="mgb20" v-html="$t('hd.实际数量已超过预计数量，请先与用户沟通确认')"></div>

        <div>
          <el-button type="primary" @click="addOverGoodsNum(false)">{{ $t('common.继续') }}</el-button>
          <el-button @click="goodsNumOverDialog1 = false">{{ $t('common.cancel') }}</el-button>
          <el-button @click="addOverGoodsNum(true)">{{ $t('hd.The current SKU no longer prompts') }}</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="goodsNumOverDialog2" :title="$t('hd.实际数量已超过预计数量')" width="400px">
      <div style="margin-top: -20px">
        <div class="mgb20">
          {{ $t('hd.当前SKU还存在于其他工单中，是否为您直接切换到对应工单？') }}
        </div>
        <template v-if="currentWorkType === workTypeMap.tallying">
          <el-radio-group v-model="selectShipmentId" class="mgb10">
            <el-radio v-for="shipment in shipmentList" :key="shipment.id" :label="shipment.id" style="margin-bottom: 5px">
              {{ shipment.shipmentNo }}
            </el-radio>
          </el-radio-group>
        </template>
        <template v-else-if="currentWorkType === workTypeMap.transfer">
          <el-radio-group v-model="selectShipmentId" class="mgb10">
            <el-radio v-for="transfer in transferList" :key="transfer.id" :label="transfer.id" style="margin-bottom: 5px">
              {{ transfer.workNo }}
            </el-radio>
          </el-radio-group>
        </template>
        <template v-else-if="currentWorkType === workTypeMap.middle">
          <el-radio-group v-model="selectShipmentId" class="mgb10">
            <el-radio v-for="middle in middleList" :key="middle.id" :label="middle.id" style="margin-bottom: 5px">
              {{ middle.workNo }}
            </el-radio>
          </el-radio-group>
        </template>
        <template v-else-if="currentWorkType === workTypeMap.label">
          <el-radio-group v-model="selectShipmentId" class="mgb10">
            <el-radio v-for="label in labelList" :key="label.id" :label="label.id" style="margin-bottom: 5px">
              {{ label.labelNo }}
            </el-radio>
          </el-radio-group>
        </template>

        <div class="font-red mgb20">
          {{ $t('hd.选中并切换后，当前工单仅为您做保存处理，不会直接确认，您还需要重新确认') }}
        </div>

        <div>
          <el-button type="primary" @click="addOverGoodsNum(false)">{{ $t('hd.继续（当前）') }}</el-button>
          <el-button @click="changeShipment" :loading="changeShipmentLoading">
            {{ $t('hd.切换工单') }}
          </el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="scanSubOrdersDialog" title="" width="600px" class="scan-dialog">
      <div style="margin-top: -20px" class="font-orange">
        <div class="mgb20 font-bold">（{{ currentScanSubOrdersNum }}/{{ totalScanSubOrdersNum }}） {{ $t('hd.pickingText5') }}</div>
        <div style="color: #000000">{{ pickingOrder.accountType }} {{ $t('table.orderId') }}:{{ pickingOrder.orderId }}</div>
        <div v-for="(item, index) in scanPickingOrder" :key="item.id">
          ({{ index + 1 }}/{{ totalScanSubOrdersNum }}) SKU: {{ item.sku }}，
          <span :class="item.isScan ? 'font-black' : ''">{{ item.isScan ? $t('hd.scanned') : $t('hd.Not scanned') }}</span>
        </div>
        <div class="mgt20">
          {{ $t('hd.pickingText6') }}
        </div>
        <div>
          {{ $t('hd.pickingText7') }}
        </div>
        <div class="mgt20">
          {{ $t('hd.You can also2') }}：
          <el-button type="primary" @click="printerPDF">{{ $t('hd.Direct printing of face sheets') }}</el-button>
          <br />
          <span class="font-red" style="margin-left: 71px; font-size: 12px">{{ $t('hd.pickingText8') }}</span>
        </div>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="pickingNotFindGoodsDialog" :title="$t('hd.pickingText9')" width="400px">
      <div style="margin-top: -20px">
        <div>
          {{ $t('hd.pickingText10') }}
        </div>
        <div>{{ $t('hd.pickingText11') }}</div>
        <div class="mgt20 mgb20">
          <el-button @click="pickingNotFindGoodsDialog = false">{{ $t('common.cancel') }}</el-button>
          <el-button @click="switchTallying" type="danger">{{ $t('hd.Switch to inbound mode tally') }}</el-button>
        </div>
        <div style="font-size: 12px">
          {{ $t('hd.pickingText12') }}
        </div>
      </div>
    </el-dialog>

    <el-dialog :title="$t('setting.SavePackageMaterialFun Tis One')" :visible.sync="savePackageLoading" width="500px" style="max-height: 800px; overflow-y: auto">
      <div class="mgb10">
        {{ $t('setting.SavePackageMaterialFun Tis Three') }}
      </div>

      <div class="mgb10" v-for="(item_div_top, index_div_top) in copyPackageMaterialArr" :key="index_div_top">
        <div
          class="mgb10"
          v-for="(item_div, index_div) in item_div_top.numInfo"
          :key="index_div"
          style="border: 1px solid #e6ebf5; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
        >
          <div class="mgb10 mgt10 mgl10">
            <span style="font-weight: bold">SKU: {{ item_div.sku }}</span>
          </div>
          <div class="mgb10 mgl10">
            <el-button
              class="font-bold"
              @click="addPackage(0, item_div, index_div_top)"
              style="font-size: 14px; width: 200px; text-align: left"
              :type="buttonType(0, item_div)"
              :plain="isPlain(0, item_div)"
            >
              {{ $t('setting.No packaging service') }}
            </el-button>
            <span style="color: gray; margin-left: 10px">{{ acquiesceStr(0, item_div) }}</span>
          </div>
          <div class="mgb20 mgl10" v-for="(item, index) in pickingOrder.packageMaterialSetting" :key="index">
            <el-button
              class="font-bold"
              @click="addPackage(item, item_div, index_div_top)"
              style="font-size: 14px; width: 200px; text-align: left"
              :type="buttonType(item.id, item_div)"
              :plain="isPlain(item.id, item_div)"
            >
              {{ item.name }}({{ item.price }}{{ $t('setting.unit1') }})
            </el-button>
            <span style="color: gray; margin-left: 10px">{{ acquiesceStr(item.id, item_div) }}</span>
          </div>
        </div>
      </div>

      <div class="mgt20">
        <span style="font-size: 13px">{{ $t('setting.SavePackageMaterialFun Tis Six') }}</span>
      </div>
      <div>
        <span style="font-size: 13px">{{ $t('setting.SavePackageMaterialFun Tis Four') }}</span>
      </div>
      <div>
        <span style="font-size: 13px">{{ $t('setting.SavePackageMaterialFun Tis Five') }}</span>
      </div>
      <div>
        <span style="color: red; font-size: 13px">{{ $t('setting.SavePackageMaterialFun Tis Two') }}</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="savePackageLoading = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="savePackage" :loading="savePackageFormLoading" :disabled="disableButton">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog class="my-custom-dialog" :visible.sync="returnNoticeLoading" width="300">
      <div style="margin-top: -10px; margin-left: 50px; margin-bottom: 20px; color: black; font-size: 16px; font-width: 900">
        <div class="mgb20" style="color: red">
          <span v-if="pickingOrder.orderStatus === 4">{{ $t('hd.returnText8') }}</span>
          <span v-if="pickingOrder.orderStatus === 5">{{ $t('hd.returnText9') }}</span>
        </div>

        <div>
          <span>{{ pickingOrder.accountType }}{{ $t('hd.returnText11') }}：{{ pickingOrder.orderId }}</span>
        </div>

        <div class="mgb20">
          <span>
            {{ $t('hd.returnText14') }}
            <span v-if="pickingOrder.orderStatus === 4">{{ pickingOrder.cancelDate }} {{ $t('hd.returnText12') }}，</span>
            <span v-if="pickingOrder.orderStatus === 5">{{ pickingOrder.refundDate }} {{ $t('hd.returnText13') }}，</span>
            <span style="color: red">{{ $t('hd.returnText10') }}</span>
          </span>
        </div>

        <div class="mgb20" v-if="pickingOrder.orderStatus === 5">
          <div class="mgb10" v-for="(item, index) in pickingOrder.subOrders" :key="index">
            <span :style="returnNoticeTis(item)">
              {{ item.goodsId }}（{{ item.sku }}）
              <span v-if="item.isReturn">，已退货</span>
            </span>
          </div>
        </div>

        <div>
          <span style="color: #808080; font-size: 13px">{{ $t('hd.returnText7') }}</span>
        </div>
      </div>
    </el-dialog>

    <el-dialog class="my-custom-dialog" :visible.sync="goodsLabelPDFDialog" :title="$t('labelOrder.请确认导出SKU标数量')" width="600px">
      <el-form label-width="200px" :model="goodsLabelPDF">
        <el-form-item label="库存类型" v-show="labelInfo.type === 2 && !boxLabelData.isSystemLabel">
          <el-radio-group v-model="goodsLabelPDF.stockType">
            <el-radio :label="1" :disabled="goodsLabelPDF.exOneStock === 0">
              {{ $t('table.从一件代发库存调出') }}
            </el-radio>
            <el-radio :label="2" :disabled="goodsLabelPDF.exMiddleStock === 0">
              {{ $t('table.从中转送仓库存调出') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('hd.本次贴标Listing ID与SKU')">
          <el-select v-model="goodsLabelPDF.labelGoodsId" placeholder="请选择" style="width: 250px">
            <el-option v-for="item in selectLabelGoods" :key="item.id" :value="item.id" :label="`${item.toGoodsId}(${item.toSku})`"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('hd.打印数量')">
          <el-input-number v-model="goodsLabelPDF.num" :min="1" :precision="0"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsLabelPDFDialog = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="exportLabelPdf" :loading="btnLoading">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('选择物流商')" :visible.sync="logisticsDialog" width="500px" style="text-align: left" :close-on-click-modal="false" :before-close="closeLogisticsDialog">
      <template>
        <el-radio v-for="(item, index) in integratedLogisticsSettingData" :key="index" v-model="getDefaultLogisticsType" :label="item.logistics_type">
          {{ item.logistics_type }}
        </el-radio>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeLogisticsDialog">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="logisticsPrintShipping(getDefaultLogisticsType)" :loading="logisticsLoading">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('hd.货件未添加到当前货柜')" :visible.sync="installBoxDialog" width="500px" style="text-align: left" >
      <template>
         <p style="font-size: 15px;">扫描货件箱唛尚未添加到当前货柜，是否确认添加到当前货柜？</p>

      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="installBoxDialog=false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="addOtherBox" >{{ $t('common.confirm') }}</el-button>
        <p style="font-size: 12px;">若扫码结果有误，请联系技术人员处理</p>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Scanner from '@/views/scanner/index';
import { deepCopy, generateRandomString, getDomainName, getLogisticTypeTextColor, getMDAppVersion, getMDName, getOrderLogisticType, getPlatformTextColor } from '@/utils/index.js';
import { io } from 'socket.io-client';
import { v4 as uuidv4 } from 'uuid';
import JsBarcode from 'jsbarcode';
import { downLoadShipping, order2Stock, confirmAndPrintTheNewPDF, alterPackage, addPackage, removePackage } from '@/api/order';
import { isTesting,getTransferTypeName,isFirstLegRole } from '@/utils/common';
import axios from 'axios';
import OrderStatusTag from '@/views/order/components/OrderStatusTag.vue';
import request from '@/utils/request';
import {
  getBoxLabelInfo,
  getCancelReturnOrder,
  getLabelListByHM,
  getMiddleListByHM,
  getMinoShippingHWTestPDF,
  getPickOrder,
  getShipmentListByHW,
  getTestingSkuOrder,
  getTransferListByHW,
  stickerOrder
} from '@/api/hardware';
import { boxChangeContainer,boxHdChangeContainer,changeStatus, editContainerBox, finishedSorting, getContainerInfo, installBox, removeContainerBox, scanContainerBox } from '@/api/container';
import orderMixin from '@/views/order/mixin/orderMixin';
import { confirmShipment, getShipmentGoodsPage, getShipmentImgArr, getShipmentInfo, saveShipmentGoodsList, saveShipmentImg } from '@/api/shipment';
import ShipmentInfoView from '@/views/shipment/components/ShipmentInfoView';
import PackageTag from '@/views/order/components/PackageTag.vue';
import HardwarePrintSkuInfo from '@/views/minoFirstDropshipping/components/HardwarePrintSkuInfo.vue';
import ToolTipShipmentBox from '@/views/shipment/components/ToolTipShipmentBox.vue';
import { finishTransfer, getTransferInfo, saveRlGoodsNum } from '@/api/transferWork';
import { getTransferLabelStatusStr, getTransferTypeStr } from '@/utils/transferWork';
import TransferInfoView from '@/views/transferWork/components/TransferInfoView.vue';
import { getMiddleInfo, pickedMiddleWorkOrder, saveMiddleWorkRlGoodsNum } from '@/api/middleWork';
import MiddleInfoView from '@/views/middleWork/components/MiddleInfoView.vue';
import { exportLabelGoodsLabelPdf, finishLabelOrder, getLabelOrderInfo } from '@/api/labelOrder';
import { getLabelStatusStr, getLabelTypeStr } from '@/utils/labelOrder';
import LabelOrderInfoView from '@/views/labelOrder/components/LabelOrderInfoView.vue';
import { every, some } from 'core-js/internals/array-iteration';
import { getMiddleLabelStatusStr } from '@/utils/MiddleWork';
import shipmentMixin from '@/views/minoFirstDropshipping/mixin/shipmentMixin';
import labelMixin from '@/views/minoFirstDropshipping/mixin/labelMixin';
import hardware from '@/views/minoFirstDropshipping/mixin/hardware';
import GunModelSet from '@/views/minoFirstDropshipping/components/gunModelSet.vue';
import ShipmentInfoImg from '@/views/shipment/components/ShipmentInfoImg';

import { getShipmentTypeStr2 } from '@/utils/shipment';
import ContainerSteps from '@/views/container/components/ContainerSteps.vue';
import ContainerInfoTable from '@/views/container/components/ContainerInfoTable.vue';
import {PLAN_TYPE_FL, PLAN_TYPE_MW} from "@/utils/shippingPlan";
import ContainerInfoView from "@/views/container/components/containerInfoView.vue";

// 箱标
const boxLabel = {
  MIX: 'MIX', // 混箱箱标
  TB: 'TB' // 未贴标箱标
};

// 秤状态
const scalesStateMap = {
  search: 'search',
  connected: 'connected',
  discontented: 'discontented',
  error: 'error',
  transform: 'transform'
};
// 工作模式
const workTypeMap = {
  tallying: 'tallying', // 理货模式
  return: 'return', // 退货/取消模型
  picking: 'picking', // 拣货模式
  middle: 'middle', // 中转
  transfer: 'transfer', // 调货
  label: 'label' // 贴标
};

export default {
  name: 'index',
  mixins: [orderMixin, shipmentMixin, labelMixin, hardware],
  watch: {
    appCheckStatus: {
      handler(newValue, oldValue) {
        const flag =
          this.appCheckStatus.appStart &&
          this.appCheckStatus.printersState &&
          this.appCheckStatus.scalesState === scalesStateMap.transform &&
          this.appCheckStatus.appVersion === this.appVersion;
        if (flag) {
          this.appStartDialog = false;
          this.$successMessage(this.$t('hd.Hardware matching successful'));
        }
      },
      deep: true
    },
    gunStep() {
      if (this.gunStep === 3) {
        this.createGunTestString();
      }
    }
  },
  computed: {
    boxIsEveryInstall() {
      return !this.boxTable.every((item) => item.isInstall);
    },
    logisticsDetail() {
      if (!this.logistics) {
        return [];
      }
      const arr = deepCopy(this.logistics.allDetail);
      if (!this.logisticsLimit) {
        return arr;
      }
      return arr.splice(0, 5);
    },
    canCloseAppDialog() {
      return this.appCheckStatus.appStart && this.appCheckStatus.printersState && this.appCheckStatus.appVersion === this.appVersion;
    },
    // 是否都匹配成功
    isAllOk() {
      return (
        this.appCheckStatus.appStart &&
        this.appCheckStatus.printersState &&
        this.appCheckStatus.scalesState === scalesStateMap.transform &&
        this.appCheckStatus.appVersion === this.appVersion
      );
    },
    isPassTest() {
      return true;
    },
    workTypeName() {
      let name = '';
      switch (this.currentWorkType) {
        case workTypeMap.picking:
          name = this.$t('hd.出库模式 (装柜)');
          break;
        case workTypeMap.return:
          name = this.$t('hd.Warehousing mode (return/cancellation)');
          break;
        case workTypeMap.tallying:
          name = this.$t('hd.Warehousing mode (tally)');
          break;
        case workTypeMap.transfer:
          name = this.$t('hd.Warehousing mode (Transfer)');
          break;
        case workTypeMap.label:
          name = this.$t('hd.Warehousing mode (Label)');
          break;
        case workTypeMap.middle:
          name = this.$t('hd.Outbound mode (Middle)');
          break;
      }
      return name;
    },
    disableButton() {
      return JSON.stringify(this.copyPackageMaterialArr) === JSON.stringify(this.copyPackageMaterialArrTwo);
    },
    // 根据当前扫描的箱标获取当前对应的商品数据
    scanBoxLabelGoods() {
      return this.labelGoodsData.filter((item) => {
        if (this.boxLabelData.isSystemLabel) {
          return !!(item.fromGoodsIsSystem && item.systemLabelId === this.boxLabelData.systemLabelId);
        } else if (this.boxLabelData.isTB) {
          return !!(item.fromGoodsIsTB && item.fromSuitId === this.boxLabelData.suitId);
        } else {
          return item.fromSuitListId === this.boxLabelData.suitListId && this.boxLabelData.suitListId !== 0;
        }
      });
    }
  },
  data() {
    return {
      installBoxDialog:false,
      appVersion: getMDAppVersion(), // 软件的版本号
      appLink: false, // 是否启动了软件
      scalesStateMap,
      workTypeMap,
      appStartDialog: true, // app启动检测
      gunDialog: false, // 扫描枪配置
      gunTestDialog: false, // 扫描枪测试
      // 校验app相关信息
      searchKeyword: '', // 自己搜索的关键词
      // currentWorkType: '', // 当前的工作模式
      currentWorkType: workTypeMap.picking, // 当前的工作模式
      mdType: 0,
      workTypeList: [
        {
          md: 1,
          mode: this.$t('hd.Warehousing mode'),
          modeName: this.$t('hd.Tallying'),
          modeImage: require('@/assets/images/MD-tallying.png'),
          workType: workTypeMap.tallying
        },
        {
          md: 1,
          mode: this.$t('hd.Warehousing mode'),
          modeName: this.$t('hd.Returns and cancellations'),
          modeImage: require('@/assets/images/MD-return.png'),
          workType: workTypeMap.return
        },
        {
          md: 1,
          mode: this.$t('hd.Warehousing mode'),
          modeName: this.$t('hd.Transfer'),
          modeImage: require('@/assets/images/MD-transfer.png'),
          workType: workTypeMap.transfer
        },
        {
          md: 1,
          mode: this.$t('hd.Warehousing mode'),
          modeName: this.$t('hd.Label'),
          modeImage: require('@/assets/images/MD-label.png'),
          workType: workTypeMap.label
        },
        {
          md: 2,
          mode: this.$t('hd.Outbound mode'),
          modeName: this.$t('hd.picking'),
          modeImage: require('@/assets/images/MD-picking-V2.png'),
          workType: workTypeMap.picking
        },
        {
          md: 2,
          mode: this.$t('hd.Outbound mode'),
          modeName: this.$t('hd.Middle'),
          modeImage: require('@/assets/images/MD-middle.png'),
          workType: workTypeMap.middle
        }
      ],
      gunTestStr: '', // 调试的字符串
      gunScannerTest: '', // 扫描的字符
      scannerTest: '', // 扫描枪和自定义输入扫码内容
      orderLoading: false,
      orderScannerType: '', // 扫描对应的类型
      selfWeight: 0, //
      stickerLoading: false,
      selfKeyword: '',
      gunStep: 1,
      fixedScannerText: "w6'f\\`%Y?)n!]%>$", // 固定的测试码
      gunTestPDF: null,
      printerPDFType: 1,
      printerTestLoading: false,
      commonPrinterLoading: false,
      currentPrinterOrder: null,
      orderPrintList: [],
      returnOrder: {
        subOrders: []
      },
      // 退货的表单数据
      returnForm: {
        orderId: '',
        accountTypeNum: '',
        refundSticker: 0,
        selectSubOrder: [],
        refundGoods: []
      },
      // 理货
      tallyingMode: 1, // 理货模式 1：还没有任何扫描 2：多个货件 3：单个货件入库
      shipmentList: [], // 拣货单列表
      shipmentInfo: {}, // 拣货单详情
      shipmentBox: [],
      shipmentGoods: [],
      shipmentGoodsApi: [],
      shipmentGoodsParams: {
        shipmentId: 0,
        page: 1,
        pageSize: 50
      },
      currentShipmentGoods: null,
      ignoreShipmentSku: [],
      selectShipmentId: null,
      goodsNumOverDialog1: false,
      goodsNumOverDialog2: false,
      changeShipmentLoading: false, // 切换货件时的loading

      // 拣货
      pickingOrder: {
        subOrders: [], // 子订单
        showSubOrders: false // 是否展示所有子订单
      },
      pickingOrderType: '', // 用于判断扫描的是什么 商品为goods 面单为shipping
      shippingData: {},
      scanPickingOrder: [],
      scanSubOrdersDialog: false, // 多商品扫描的对话框
      currentScanSubOrdersNum: 0,
      totalScanSubOrdersNum: 0,
      currentPickingForm: {
        orderId: '',
        weight: 0, // 重量
        needPackage: false, // 是否需要包装服务
        accountTypeNum: 1, // 订单平台类型
        packageMaterial: [] // 包装包材
      },
      // 是否能打印
      canPrint: false,
      pickingNotFindGoodsDialog: false,

      // loading加载效果
      dataLoading: false,
      stockBtnLoading: false,
      confirmAndPrintTheNewBtnLoading: false,
      testingSkuLoading: false,
      shipmentLoading: false,
      savePackageLoading: false,
      //默认的包材id
      acquiescePackageMaterialId: 0,
      //已经选择的包材id
      selectPackageMaterialId: 0,
      selectPackageMaterialName: '',
      packageMaterialArr: [],
      copyPackageMaterialArr: [],
      copyPackageMaterialArrTwo: [],
      savePackageFormLoading: false,
      subPackageMaterialArr: [],
      returnNoticeLoading: false,
      // 大货中转
      scannerShipmentBox: [], // 记录已经扫描的箱标
      transferMode: 1, // 调货中的模式
      transferList: [], // 拣货单列表
      transferInfo: {}, // 拣货单详情
      straightGoods: [],
      distributionGoodsList: [],
      btnLoading: false,
      currentGoods: null,
      middleMode: 1, // 中转中的模式
      middleList: [],
      middleInfo: {},
      middleStraightGoods: [],
      middleDistributionGoodsList: [],
      labelMode: 1, // 调货模式
      labelList: [],
      labelInfo: {},
      labelGoodsData: [],
      boxLabelData: {
        id: 0, // 箱子id shipmentGoodsId
        shipmentId: 0, // 货件单id
        boxNumber: 0, // 第几个箱子
        suitId: 0,
        suitListId: 0, // 商品的id
        goodsBoxNum: 0, // 箱装数
        isSystemLabel: false, // 是不是系统标
        systemLabelId: 0, // 系统标对应的id
        isTB: false, // 是不是贴标箱子
        isMix: false, // 是不是混箱箱标
        isBox: false, // 是不是箱标
        isScan: false, // 是否扫描入库了
        boxVersion: 'v1', // 当前箱标的版本
        containerId: 0, // 货柜id
        planId: 0, // 发货计划id
        planType: '', // 发货计划类型
      }, // 扫描箱标的内容
      goodsLabelPDFDialog: false,
      goodsLabelPDF: {
        stockType: 1, // 库存类型 1从一件代发调出 2从中转送仓调出
        labelGoodsId: 0, // 当前的id
        num: 0, // 当前的要打印的数量
        exOneStock: 0,
        exMiddleStock: 0
      },
      selectLabelGoods: [],
      gunTestModel: false,
      updateImgUrl: '',
      logisticsDialog: false,
      logisticsLoading: false,
      integratedLogisticsSettingData: [],
      getDefaultLogisticsType: '',
      copyGetDefaultLogisticsType: '',
      data: {},
      boxTable: [],
      history: [],
      logistics: null,
      editDialog: false,
      dialogForm: {
        type: 'add',
        boxIds: ''
      },
      digBtnLoading: false,
      editFailDialog: false,
      notFoundBox: [],
      otherBox: [], // 其他货件的箱唛
      diffTypeBox: [], // 不同运输类型的箱唛
      logisticsLimit:true,
      containerData: {},
    };
  },
  methods: {
    isFirstLegRole,
    getTransferTypeName,
    saveShipmentImg,
    getShipmentImgArr,
    getLabelStatusStr,
    getMiddleLabelStatusStr,
    getLabelTypeStr,
    getTransferLabelStatusStr,
    getTransferTypeStr,
    getLogisticTypeTextColor,
    getOrderLogisticType,
    getPlatformTextColor,
    getMDName,
    isTesting,
    async scannerInput(text) {
      if (this.gunTestModel) {
        this.gunScannerTest = text;
      } else if (text === this.fixedScannerText) {
        this.$successMessage(this.$t('hd.The scanning gun is operating normally'));
      } else {
        // 没有设置任何模式 不处理
        if (this.currentWorkType === '') {
          return;
        }
        this.scannerTest = text;
        await this.setBoxLabelData(); // 设置箱标数据
        // 重新扫描时 关闭所有dialog
        this.closeAllDialog();
        switch (this.currentWorkType) {
          case workTypeMap.return: // 退货模式
            this.getReturnOrder();
            break;
          case workTypeMap.tallying: // 理货模式
            this.getTallyingData();
            break;
          case workTypeMap.picking:
            if (this.pickingOrderType == 1) {
              this.installRow();
            } else {
              this.getContainerData();
            }
            break;
          case workTypeMap.transfer:
            this.getTransferData();
            break;
          case workTypeMap.middle:
            this.getMiddleData();
            break;
          case workTypeMap.label:
            this.getLabelData();
            break;
        }
      }
    },
    // 改变gunTestModel的值
    changeGunScannerTestValue(value) {
      this.gunTestModel = value;
    },
    /**
     * 获取域名
     * @returns {string}
     */
    getDomainName() {
      const name = getDomainName();
      return String(name.charAt(0).toUpperCase() + name.slice(1));
    },
    // 生成随机的字符串
    createGunTestString() {
      this.gunTestStr = generateRandomString(16, true);
      setTimeout(() => {
        JsBarcode('#barcode', this.gunTestStr, {
          width: 2,
          height: 100,
          fontSize: 20
        });
        this.$refs.testInput.focus();
      }, 0);
    },
    // 获取相关信息
    getReturnOrder(keyword = false) {
      const params = {
        keyword: keyword ? this.selfKeyword : this.scannerTest
      };
      if (!params.keyword) {
        return;
      }
      this.dataLoading = true;
      getCancelReturnOrder(params).then((res) => {
        this.dataLoading = false;
        if (res.error !== 0) {
          this.$errorMessage(res.message);
          return;
        }

        const data = deepCopy(res.data);
        this.returnForm.selectSubOrder = [];
        this.returnForm.refundGoods = [];
        data.subOrders.forEach((item) => {
          this.returnForm.selectSubOrder.push(item.subOrderId);
          this.returnForm.refundGoods.push({
            subOrderId: item.subOrderId,
            num: data.toStock === -1 ? item.num : item.returnNum
          });
        });
        this.returnForm.orderId = data.orderId;
        this.returnForm.accountTypeNum = data.accountTypeNum;
        this.returnForm.refundSticker = data.toStock === -1 ? 0 : data.refundSticker;

        this.returnOrder = data;
      });
    },
    // 打印pdf文件
    printerPDF() {
      if (this.pickingOrder.flowType === 'integratedLogistics') {
        if (this.pickingOrder.isLogisticsComplete === false) {
          this.getDefaultLogisticsType = this.copyGetDefaultLogisticsType;
          this.logisticsDialog = true;
          return;
        }
      }

      if (!this.currentPrinter) {
        this.$errorMessage(this.$t('hd.Please select a printer'));
        return;
      }
      this.currentPrinterStatus = 1;
      this.canPrint = true;
      this.scanSubOrdersDialog = false;

      const params = {
        orderId: this.pickingOrder.orderId,
        accountTypeNum: this.pickingOrder.accountTypeNum
      };

      request({
        url: `/hardware/getOrderPdf`,
        responseType: 'arraybuffer', // 需要加上
        isNotJson: true,
        timeout: 10000,
        handleResponse: true,
        params
      }).then((res) => {
        if (res.headers['content-type'].match(/application\/pdf/) && res.status === 200) {
          this.currentPrinterStatus = 2;

          const data = {
            pdfData: res.data,
            printerName: this.currentPrinter.name
          };
          this.sendSocket('print', data, null);
        } else {
          this.currentPrinterStatus = -1;

          // 步骤1：将 ArrayBuffer 解码为字符串
          // const decoder = new TextDecoder('utf-8');
          // const jsonString = decoder.decode(new Uint8Array(res.data));

          // 步骤2：将字符串解析为 JavaScript 对象
          // const jsonObject = JSON.parse(jsonString);
        }
      });
    },
    // 打印PDF文件
    sendPrint(buffer) {
      this.currentPrinterStatus = 2;
      if (!this.currentPrinter) {
        this.$errorMessage(this.$t('hd.The current system has not configured a printer'));
        return;
      }
      const data = {
        pdfData: buffer,
        printerName: this.currentPrinter.name
      };
      // if(isTesting()){
      //   return;
      // }
      this.sendSocket('print', data, null);
    },
    printSuccess() {
      if (this.printerPDFType === 2) {
        this.printerTestLoading = false;
      }
    },
    printError() {},
    showGunDialog() {
      this.gunStep = 1;
      this.gunDialog = true;
    },
    async printGunTest() {
      if (!this.currentPrinter) {
        this.$errorMessage(this.$t('hd.There is currently no printer available'));
        return;
      }
      if (!this.gunTestPDF) {
        await getMinoShippingHWTestPDF().then((res) => {
          this.gunTestPDF = res.data;
        });
      }

      const data = {
        pdfData: this.gunTestPDF,
        printerName: this.currentPrinter.name
      };
      this.printerPDFType = 2;
      this.printerTestLoading = true;
      this.sendSocket('print', data);
    },
    startApp() {
      window.open('minoshippinghardware://');
    },
    testPrinter() {
      console.log(this.printers);
      console.log(this.currentPrinter);
    },
    // 切换模式
    resetWorkType() {
      this.currentWorkType = '';
      this.mdType = 0;
    },
    // 选择模式
    selectWorkType(row) {
      this.currentWorkType = row.workType;
      this.mdType = row.md;
    },
    // 自己搜索
    searchBySelf() {
      this.scannerInput(this.selfKeyword);
    },
    // 取消按钮 重置数据
    cancelOp() {
      this.returnOrder = {
        subOrders: []
      };
      this.shipmentGoods = [];
      this.shipmentInfo = {};
      this.shipmentBox = [];
      if (this.currentWorkType === workTypeMap.tallying) {
        this.tallyingMode = 1;
      }
      this.pickingOrder = {
        subOrders: []
      };
      this.pickingOrderType = '';
      this.transferMode = 1;
      this.transferList = [];
      this.transferInfo = {};
      this.straightGoods = [];
      this.distributionGoodsList = [];
      this.middleMode = 1;
      this.middleList = [];
      this.middleStraightGoods = [];
      this.middleDistributionGoodsList = [];
      this.labelMode = 1;
      this.labelList = [];
      this.labelInfo = {};
      this.labelGoodsData = [];
      this.scannerShipmentBox = [];
      this.containerData = {};
    },
    // 订单库存退货
    backStock() {
      this.$confirm('', this.$t('hd.Are you sure to convert to inventory?'), {})
        .then((res) => {
          this.stockBtnLoading = true;
          order2Stock(this.returnForm).then((res) => {
            this.stockBtnLoading = false;
            if (res.error === 0) {
              this.$successMessage(res.message);
              this.getReturnOrder(this.returnForm.orderId);
              this.$store.dispatch('user/getInfo');
            } else {
              this.$errorMessage(res.message);
            }
          });
        })
        .catch(() => {});
    },
    //确认并打印新标签
    confirmAndPrintTheNewLabel() {
      this.$confirm('', '确认并打印新标签?', {})
        .then((res) => {
          this.confirmAndPrintTheNewBtnLoading = true;
          confirmAndPrintTheNewPDF(this.returnOrder).then((res) => {
            this.confirmAndPrintTheNewBtnLoading = false;
            if (res.type === 'application/json') {
              this.$message({
                message: '打印新标签失败，请稍后再尝试',
                duration: 5000,
                type: 'error',
                showClose: true
              });
              return;
            }

            // 打印机打印
            const data = {
              pdfData: res.data,
              printerName: this.currentPrinter.name
            };
            this.sendSocket('print', data, null);
          });
        })
        .catch(() => {});
    },
    handleChildData(res) {
      // 打印机打印
      const data = {
        pdfData: res,
        printerName: this.currentPrinter.name
      };
      this.sendSocket('print', data, null);
      this.backStock();
    },
    getTallyingData(keyword = false) {
      const currentKeyword = keyword ? keyword : this.scannerTest;
      if (!currentKeyword) {
        return;
      }
      if (this.tallyingMode !== 3) {
        this.getShipmentList(currentKeyword);
      } else {
        this.addRlGoodsNum(currentKeyword);
      }
    },
    // 获取对应的货件单
    getShipmentList(keyword) {
      const params = {
        keyword: keyword
      };
      this.dataLoading = true;
      getShipmentListByHW(params).then((res) => {
        this.dataLoading = false;
        if (res.error !== 0) {
          this.$errorMessage(res.message);
          return;
        }
        const { data } = res;
        if (data.length === 1) {
          this.getShipmentInfo(data[0].id);
          return;
        }
        this.tallyingMode = 2;
        this.shipmentList = deepCopy(data);
      });
    },
    // 获取货件单详情
    getShipmentInfo(shipmentId, addNum = true) {
      this.dataLoading = true;
      if (shipmentId !== this.shipmentInfo.id) {
        this.ignoreShipmentSku = [];
        this.scannerShipmentBox = [];
      }
      getShipmentInfo(shipmentId).then((res) => {
        this.dataLoading = false;
        this.tallyingMode = 3;
        this.shipmentInfo = deepCopy(res.data);
        this.updateImgUrl = res.info.updateImgUrl;

        this.shipmentBox = [];
        res.data.shipmentBox.forEach((item) => {
          // item.rlBoxNum = item.rlBoxNum === null ? undefined : item.rlBoxNum
          item.rlBoxNum = res.data.status === 0 && res.data.saveBox === 0 ? 0 : item.rlBoxNum;
          this.shipmentBox.push(item);
        });

        this.shipmentGoods = [];

        // 计算一共有多少页 请求数据
        this.shipmentGoodsApi = [];
        let totalPage = Math.ceil(res.info.shipmentGoodsTotal / this.shipmentGoodsParams.pageSize);
        for (let page = 1; page <= totalPage; page++) {
          const params = {
            page: page,
            pageSize: this.shipmentGoodsParams.pageSize,
            shipmentId: this.shipmentInfo.id
          };
          this.shipmentGoodsApi.push(false);
          this.getShipmentGoods(params, addNum);
        }

        // 对应的货件数+1
        // if(addNum){
        //   this.addRlGoodsNum(this.scannerTest)
        // }
      });
    },
    getShipmentGoods(params, addNum) {
      this.dataLoading = true;
      getShipmentGoodsPage(params).then((res) => {
        res.data.forEach((item) => {
          item.rlGoodsBoxNum = item.rlGoodsBoxNum === null ? 0 : item.rlGoodsBoxNum;
          item.rlGoodsMixinNum = item.rlGoodsMixinNum === null ? 0 : item.rlGoodsMixinNum;
          item.rlGoodsNum = item.rlGoodsNum === null ? 0 : item.rlGoodsNum;
          this.shipmentGoods.push(item);
        });
        this.shipmentGoodsApi[params.page - 1] = true;
        if (this.shipmentGoodsApi.every((item) => item)) {
          this.dataLoading = false;
          // 对应的货件数+1
          if (addNum) {
            this.addRlGoodsNum(this.scannerTest);
          }
        }
      });
    },
    // 根据扫描的sku增加数量
    addRlGoodsNum(currentText) {
      if (this.boxLabelData.isBox) {
        if (this.boxLabelData.isScan) {
          this.$errorMessage(this.$t('hd.该箱标已经扫描了'));
          return;
        }

        if (this.boxLabelData.isMix) {
          // 添加过扫描的记录
          // this.scannerShipmentBox.push(currentText)
          this.shipmentBox.some((item) => {
            if (item.boxType === 5) {
              item.rlBoxNum++;
              this.$successMessage(this.$t('shipment.混箱') + '+1');
              this.saveShipmentBoxV2(item, this.shipmentInfo.id);
              this.saveBoxLabelScan(currentText);
              return true;
            }
          });
          return;
        } else {
          // 确认为箱标
          const shipmentGoodsId = this.boxLabelData.id; // 找到对应的id
          const row = this.shipmentGoods.find((item) => item.id === shipmentGoodsId);
          if (row) {
            // this.scannerShipmentBox.push(currentText)
            row.rlGoodsBoxNum++;
            let goodsStr = `${row.goodsId}(${row.sku})`;
            if (row.isSystemLabel) {
              goodsStr = `${this.$t('shipment.System label')}(${row.sku})`;
            } else if (row.isTB) {
              goodsStr = `${this.$t('shipment.Not labeled')}(${row.sku})`;
            }
            const text = `${goodsStr} + ${row.goodsNumInBox}`;
            this.$successMessage(text);
            this.shipmentBox.some((item) => {
              if (item.boxType === 4) {
                item.rlBoxNum++;
                this.saveShipmentBoxV2(item, this.shipmentInfo.id);
                this.saveShipmentGoods(row);
                this.saveBoxLabelScan(currentText); // 标记箱标被扫描
                return true;
              }
            });
            return;
          }
        }
      }
      const findGoods = this.shipmentGoods.some((goods) => {
        if ((goods.isSystemLabel && (goods.sku === currentText || goods.barcode === currentText)) || goods.inventoryId === currentText) {
          let rlGoodsNum = goods.rlGoodsNum;
          if (rlGoodsNum + 1 > goods.exGoodsNum && this.ignoreShipmentSku.indexOf(currentText) === -1) {
            this.currentShipmentGoods = goods;
            this.currentGoods = goods;
            this.goodsNumOver(goods);
          } else {
            this.addGoodsNum(goods);
          }
          this.saveShipmentGoods(goods);
          return true;
        }
      });
      // 没有查询到对应的sku 弹窗提示
      if (!findGoods) {
        this.$alert(
          `
            <p><span >${this.$t('hd.TallyingText7')}</span></p>
            <p style="color: #FF0000">${this.$t('hd.TallyingText6')}</p>
            `,
          this.$t('hd.SKU does not exist in the waybill'),
          {
            dangerouslyUseHTMLString: true,
            // type:'warning',
            showCancelButton: true,
            cancelButtonText: this.$t('hd.Cancel receipt'),
            cancelButtonClass: 'el-button--primary',
            confirmButtonText: this.$t('hd.Switch to outbound mode'),
            confirmButtonClass: 'el-button--danger'
          }
        )
          .then((res) => {
            //
            this.cancelOp();
            const data = {
              goodsList: []
            };
            this.shipmentGoods.forEach((item) => {
              if (item.rlGoodsNum !== undefined) {
                data.goodsList.push({
                  id: item.id,
                  rlGoodsNum: item.rlGoodsNum
                });
              }
            });
            saveShipmentGoodsList(data).then((res) => {
              this.changeShipmentLoading = false;
              if (res.error === 0) {
                this.currentWorkType = workTypeMap.picking;
                this.scannerInput(this.scannerTest);
              } else {
                this.$errorMessage(res.message);
              }
            });
          })
          .catch((res) => {});
      }
    },
    // 添加数量
    addGoodsNum(goods) {
      if (this.currentWorkType === workTypeMap.transfer) {
        this.transferAddGoodsNum(goods);
        return;
      }
      if (this.currentWorkType === workTypeMap.middle) {
        this.middleAddGoodsNum(goods);
        return;
      }
      if (this.currentWorkType === workTypeMap.label) {
        this.addLabelGoodsNum();
      }

      if (goods.rlGoodsMixinNum === undefined) {
        goods.rlGoodsMixinNum = 0;
      }
      goods.rlGoodsMixinNum++;
      let message = `${goods.goodsId}(${goods.sku})  +1`;
      if (goods.isSystemLabel) {
        message = `${this.$t('shipment.System label')}(${goods.sku})  +1`;
      } else if (goods.isTB) {
        message = `${this.$t('shipment.Not labeled')}(${goods.sku})  +1`;
      }
      this.$successMessage(message);
    },
    // 当前数量超过了提示
    goodsNumOver(goods) {
      getShipmentListByHW({
        keyword: goods.sku,
        currentId: this.shipmentInfo.id
      }).then((res) => {
        const { data } = res;
        this.shipmentList = data;
        if (data.length === 0) {
          this.goodsNumOverDialog1 = true;
        } else {
          this.selectShipmentId = data[0].id;
          this.goodsNumOverDialog2 = true;
        }
      });
    },
    // 通知入库数量超过了预计入库数量
    addOverGoodsNum(flag = false) {
      if (!this.currentGoods) {
        return;
      }
      this.addGoodsNum(this.currentGoods);
      // 忽略下一次提示
      if (flag) {
        this.ignoreShipmentSku.push(this.currentGoods.sku);
        this.ignoreShipmentSku.push(this.scannerTest);
      }
      this.goodsNumOverDialog1 = false;
      this.goodsNumOverDialog2 = false;
    },
    // 切换货件单
    changeShipment() {
      this.changeShipmentLoading = true;
      if (this.currentWorkType === workTypeMap.tallying) {
        const data = {
          goodsList: []
        };
        this.shipmentGoods.forEach((item) => {
          if (item.rlGoodsNum !== undefined) {
            data.goodsList.push({
              id: item.id,
              rlGoodsNum: item.rlGoodsNum
            });
          }
        });
        saveShipmentGoodsList(data).then((res) => {
          this.changeShipmentLoading = false;
          if (res.error === 0) {
            this.goodsNumOverDialog2 = false;
            this.getShipmentInfo(this.selectShipmentId);
          } else {
            this.$errorMessage(res.message);
          }
        });
      }

      if (this.currentWorkType === workTypeMap.transfer) {
        const data = {
          id: this.transferInfo.id,
          goodsData: []
        };
        this.straightGoods.forEach((item) => {
          data.goodsData.push({
            id: item.id,
            rlGoodsNum: item.rlGoodsNum ? item.rlGoodsNum : 0
          });
        });

        saveRlGoodsNum(data).then((res) => {
          this.changeShipmentLoading = false;
          if (res.error === 0) {
            this.goodsNumOverDialog2 = false;
            this.getTransferInfo(this.selectShipmentId);
          } else {
            this.$errorMessage(res.message);
          }
        });
      }

      if (this.currentWorkType === workTypeMap.middle) {
        const data = {
          id: this.middleInfo.id,
          goodsData: []
        };
        this.middleStraightGoods.forEach((item) => {
          data.goodsData.push({
            id: item.id,
            rlGoodsNum: item.rlGoodsNum ? item.rlGoodsNum : 0
          });
        });

        saveMiddleWorkRlGoodsNum(data).then((res) => {
          this.changeShipmentLoading = false;
          if (res.error === 0) {
            this.goodsNumOverDialog2 = false;
            this.getMiddleInfo(this.selectShipmentId);
          } else {
            this.$errorMessage(res.message);
          }
        });
      }

      if (this.currentWorkType === workTypeMap.label) {
        // 保存当前数据 TODO ..

        this.getLabelInfo(this.selectShipmentId);
      }
    },
    // 切换到理货模式
    switchTallying() {
      this.pickingNotFindGoodsDialog = false;
      this.cancelOp();
      this.tallyingMode = 1;
      this.currentWorkType = workTypeMap.tallying;
      this.getTallyingData();
    },
    // 保存货件后重新加载货件数据
    changeShipmentData() {
      this.getShipmentInfo(this.shipmentInfo.id, false);
    },
    // 获取拣货模式数据
    getPickingData(keyword = false) {
      const params = {
        keyword: keyword ? this.selfKeyword : this.scannerTest,
        logisticsType: this.getDefaultLogisticsType
      };
      if (!params.keyword) {
        return;
      }
      this.dataLoading = true;
      scanContainerBox(params).then((res) => {
        this.dataLoading = false;
        this.logisticsLoading = false;
        this.logisticsDialog = false;
        if (res.error === 0) {
          if(res.data.status!='wait_make_cabinet'){
             this.$errorMessage('当前扫描货件箱唛为非待装柜货件，请重新扫描。若扫描结果有误，请联系技术人员处理。');
             return;
          }
          this.data = res.data;
          this.history = this.data.history;
          this.boxTable = res.data.boxList;
          this.logistics = res.data.logistics;
          //首次扫描装柜
          if (this.pickingOrderType == '') {
            this.pickingOrderType = 1; //初始扫描
            this.installRow(keyword);
            return;
          }
        } else {
          this.$errorMessage(res.message);
        }
      });
    },
    getContainerData(keyword = false){
      let currentKeyword = keyword ? this.selfKeyword : this.scannerTest;
      if(!this.boxLabelData.isBox){
        this.$eMsg('未匹配到对应的箱唛数据');
        return;
      }
      // 头程是分拣货柜箱唛
      const planType = this.boxLabelData.planType
      if(planType === PLAN_TYPE_FL){
        if(!this.boxLabelData.containerId){
          this.$eMsg(this.boxLabelData.boxId + '箱唛尚未分配货柜');
          return;
        }
        this.getContainer(this.boxLabelData.containerId, currentKeyword)
      }else{
        this.$eMsg(this.boxLabelData.boxId + '非头程箱唛')
      }
    },
    // 获取对应的货柜
    getContainer(id, scanBox = ''){
      this.dataLoading = true;
      getContainerInfo(id)
        .then(res=>{
          this.dataLoading = false
          this.containerData = res.data
          this.pickingOrderType = 1;
          if(scanBox){
            this.installRow(scanBox)
          }
        })
    },
    //扫描装柜
    installRow(keyword = false) {
      installBox({
        id: this.containerData.id,
        boxId: keyword ? this.selfKeyword : this.scannerTest
      }).then((res) => {
        if(res.error==201){
            this.$errorMessage(res.message);
            return;
        }
        if(res.error==202){
            this.$errorMessage('当前扫描货件箱唛为非待装柜货件，请重新扫描。若扫描结果有误，请联系技术人员处理。');
            return;
        }
        if(res.error==203){
            this.otherBox.push(
            {
              'boxId':keyword ? this.selfKeyword : this.scannerTest,
              'containerId':res.data

            });
            this.installBoxDialog=true;
            return;
        }
        this.$successMessage('扫描成功');
        this.getContainer(this.containerData.id);
      });
    },
    //确认已装柜
    finishBox() {
      changeStatus({
        id: this.data.id,
        status: 'wait_customs_declaration' // 待报关
      }).then((res) => {
        if (res.error === 0) {
            this.cancelOp();
          this.$successMessage(res.message);
        }
      });
    },
    showEditDialog() {
      this.editDialog = true;
      this.dialogForm.type = 'add';
      this.dialogForm.boxIds = '';
    },
    submitDialogForm() {
      const data = {
        id: this.data.id,
        type: this.dialogForm.type,
        boxIds: []
      };
      data.boxIds = this.dialogForm.boxIds.split('\n');
      data.boxIds = data.boxIds.map((item) => item.trim()).filter((item) => item);
      if (!data.boxIds.length) {
        this.$errorMessage('请输入箱唛');
        return;
      }
      this.digBtnLoading = true;
      this.notFoundBox = [];
      this.otherBox = [];
      this.diffTypeBox = [];
      editContainerBox(data).then((res) => {
        this.digBtnLoading = false;
        if (res.error === 0) {
          this.notFoundBox = res.data.notFound || [];
          this.otherBox = res.data.otherContainer || [];
          this.diffTypeBox = res.data.transferTypeDiff || [];
          this.getPickingData();
          if (this.notFoundBox.length > 0 || this.otherBox.length > 0 || this.diffTypeBox.length > 0) {
            this.editFailDialog = true;
          } else {
            this.$successMessage(res.message);
          }
          this.editDialog = false;
        } else {
          this.$errorMessage(res.message);
        }
      });
    },
    // 将其他货柜箱唛添加到当前货柜
    addOtherBox() {
      // 没有箱唛
      if (this.otherBox.length <= 0) {
        return;
      }
      const data = {
        id: this.containerData.id,
        boxIds: this.otherBox
      };
      boxHdChangeContainer(data).then((res) => {
        if (res.error === 0) {
          this.editFailDialog = false;
          this.installBoxDialog=false;
          this.getContainer(this.containerData.id);
          this.$successMessage(res.message);
        } else {
          this.$errorMessage(res.message);
        }
      });
    },
    getPackageMaterialArr(res) {
      //计算包材显示数据
      this.packageMaterialArr = [];

      if (res.data.packageMaterialInfo !== undefined && res.data.packageMaterialInfo !== null && res.data.packageMaterialInfo.length > 0) {
        this.packageMaterialArr = res.data.packageMaterialInfo;
      } else {
        res.data.subOrders.forEach((row, index) => {
          let numInfo = [];
          for (let i = 0; i < row.num; i++) {
            let skuPackageMaterialInfo = {
              //用户设置包材id
              acquiescePackageMaterialId: row.packageMaterialData.package_material_id,
              sku: row.sku,
              selectPackageMaterialId: '',
              selectPackageMaterialName: '',
              number: i + 1
            };
            numInfo.push(skuPackageMaterialInfo);
          }

          let skuPackageMaterial = {
            sku: row.sku,
            num: row.num,
            index: index,
            numInfo: numInfo
          };
          this.packageMaterialArr.push(skuPackageMaterial);
        });
      }

      this.getSubPackageMaterialArr();
    },
    getSubPackageMaterialArr() {
      let subPackageTag = [];
      this.packageMaterialArr.forEach((row) => {
        let map = new Map();
        row.numInfo.forEach((rowItem) => {
          if (map.has(rowItem.selectPackageMaterialName)) {
            map.set(rowItem.selectPackageMaterialName, map.get(rowItem.selectPackageMaterialName) + 1);
          } else {
            map.set(rowItem.selectPackageMaterialName, 1);
          }
        });
        for (const [i, v] of map.entries()) {
          if (i !== '') {
            let subPackageTagItem = {};
            subPackageTagItem['sku'] = row.sku;
            if (v > 1) {
              subPackageTagItem['tagTitle'] = i + 'x' + v;
            } else {
              subPackageTagItem['tagTitle'] = i;
            }
            subPackageTagItem['tagTitleInfo'] = i;
            let index = this.pickingOrder.packageMaterialSetting.findIndex((obj) => obj.name === i);
            subPackageTagItem['tagTitleInfoNum'] = index + 1;
            subPackageTagItem['skuIndex'] = row.index;
            subPackageTag.push(subPackageTagItem);
          }
        }
      });

      this.subPackageMaterialArr = subPackageTag;
    },
    // 展示sku/收起sku
    changeOrderShow() {
      this.pickingOrder.showSubOrders = !this.pickingOrder.showSubOrders;
    },

    // 确认入库
    submitStickerForm() {
      let stickerWeight = this.selfWeight !== 0 ? this.selfWeight : this.scalesWeight;
      if (!stickerWeight) {
        this.$errorMessage(this.$t('hd.Abnormal product weight'));
        return;
      }
      if (!this.currentPickingForm.orderId) {
        this.$errorMessage(this.$t('hd.Order parameters are abnormal. Please contact the administrator'));
        return;
      }
      this.stickerLoading = true;
      const postData = {
        orderId: this.currentPickingForm.orderId,
        stickerWeight: stickerWeight,
        needPackage: this.currentPickingForm.needPackage,
        accountTypeNum: this.currentPickingForm.accountTypeNum,
        packageMaterial: this.currentPickingForm.packageMaterial
      };
      stickerOrder(postData).then((res) => {
        this.stickerLoading = false;
        if (res.error === 0) {
          this.$successMessage(res.message);
          // 再请求订单数据
          this.getPickingData();
          // this.$store.dispatch('user/getInfo')
        } else {
          this.$errorMessage(res.message);
        }
      });
    },
    // 校验是否能打印面单
    checkPrinterPdf() {
      this.scanSubOrdersDialog = false;
      this.totalScanSubOrdersNum = 0;
      this.currentScanSubOrdersNum = 0;

      // 统计当前被扫描的商品
      this.scanPickingOrder.forEach((item) => {
        this.totalScanSubOrdersNum++;
        if (item.isScan) {
          this.currentScanSubOrdersNum++;
        }
      });

      // 判断是否要显示对话框
      if (this.totalScanSubOrdersNum === this.currentScanSubOrdersNum && this.currentScanSubOrdersNum !== 0) {
        this.scanSubOrdersDialog = false;
        this.printerPDF();
      } else {
        if (this.pickingOrder.flowType === 'integratedLogistics') {
          if (this.pickingOrder.isLogisticsComplete === true) {
            if (this.pickingOrder.flowType === '') {
              this.scanSubOrdersDialog = this.scanPickingOrder.length !== 1;
            }
            if (this.scanPickingOrder.length === 1) {
              this.printerPDF();
            }
          } else {
            if (this.pickingOrder.logisticsNum <= 0) {
              // 无配置物流情况
              this.$errorMessage('无面单订单,请先联系管理人员开启物流商');
            }
            if (this.pickingOrder.logisticsNum > 1) {
              // 多个物流商
              this.integratedLogisticsSettingData = this.pickingOrder.logisticsList;
              this.getDefaultLogisticsType = this.pickingOrder.logisticsType;
              this.copyGetDefaultLogisticsType = this.pickingOrder.logisticsType;
              this.logisticsDialog = true;
            }
          }
        } else {
          if (this.pickingOrder.flowType === '') {
            this.scanSubOrdersDialog = this.scanPickingOrder.length !== 1;
          }
          if (this.scanPickingOrder.length === 1) {
            this.printerPDF();
          }
        }
      }
    },
    // 关闭所有dialog
    closeAllDialog() {
      this.pickingNotFindGoodsDialog = false;
      this.scanSubOrdersDialog = false;
      this.goodsNumOverDialog1 = false;
      this.goodsNumOverDialog2 = false;
    },
    getTestingSku(type) {
      this.testingSkuLoading = true;
      const params = {
        type: type
      };
      getTestingSkuOrder(params).then((res) => {
        this.testingSkuLoading = false;
        if (res.error !== 0) {
          this.$errorMessage(res.message);
          return;
        }
        this.scannerInput(res.data.sku);
      });
    },
    // 自定义扫描内容
    diyScan() {
      this.scannerInput(this.selfKeyword);
    },
    // 校验是否能提交表单
    checkShipment() {
      const flag =
        this.shipmentBox.every((item) => item.rlBoxNum === item.exBoxNum) &&
        this.shipmentGoods.every((item) => {
          if (this.shipmentInfo.type === 1) {
            return true;
          }
          return item.rlGoodsMixinNum === item.exGoodsMixinNum && item.rlGoodsBoxNum === item.exGoodsBoxNum;
        });
      if (!flag) {
        this.$alert(`<p><span style="color: #FF0000">${this.$t('shipment.confirmText1')}</span></p>`, this.$t('shipment.saveInfoTitle'), {
          dangerouslyUseHTMLString: true,
          // type:'warning',
          showCancelButton: true
        })
          .then((res) => {
            //
            this.submitShipment();
          })
          .catch((res) => {});
      } else {
        this.submitShipment();
      }
    },
    // 确认入库
    submitShipment() {
      this.shipmentLoading = true;
      const postData = {
        id: this.shipmentInfo.id,
        shipmentBox: this.shipmentBox,
        shipmentGoods: this.shipmentGoods,
        remark: this.shipmentInfo.remark
      };

      confirmShipment(postData).then((res) => {
        this.shipmentLoading = false;
        if (res.error === 0) {
          this.$store.dispatch('user/getInfo');
          this.$successMessage(res.message);
          this.cancelOp();
        } else {
          this.$errorMessage(res.message);
        }
      });
    },

    //添加包装服务
    addPackage(item, item_div, index_div_top) {
      const idToFind = item_div.sku;

      let objToFind = false;
      //sku为空的情况
      if (idToFind === '') {
        objToFind = this.copyPackageMaterialArr[index_div_top];
      } else {
        objToFind = this.copyPackageMaterialArr.find((obj) => obj.sku === idToFind);
      }

      if (objToFind) {
        const idToFindItem = item_div.number;

        const objToFindItem = objToFind.numInfo.find((obj) => obj.number === idToFindItem);
        if (item === 0) {
          objToFindItem.selectPackageMaterialId = '';
          objToFindItem.selectPackageMaterialName = '';
        } else {
          objToFindItem.selectPackageMaterialId = item.id;
          objToFindItem.selectPackageMaterialName = item.name;
        }
      }
      this.copyPackageMaterialArr.map((obj) => (obj.sku === idToFind ? obj : obj));
    },

    openSavePackage() {
      this.savePackageLoading = true;
      this.copyPackageMaterialArr = deepCopy(this.packageMaterialArr);
      this.copyPackageMaterialArrTwo = deepCopy(this.packageMaterialArr);
    },

    savePackage() {
      this.$confirm(this.$t('order.savePackMTextOne'), this.$t('order.save') + '?')
        .then(() => {
          this.savePackageFormLoading = true;

          let info = false;
          this.copyPackageMaterialArr.forEach((row) => {
            row.numInfo.forEach((rowItem) => {
              if (rowItem.selectPackageMaterialId !== undefined && rowItem.selectPackageMaterialId !== '') {
                info = true;
              }
            });
          });

          if (info) {
            this.currentPickingForm.needPackage = true;
            this.currentPickingForm.packageMaterial = this.copyPackageMaterialArr;
          } else {
            this.currentPickingForm.needPackage = false;
            this.currentPickingForm.packageMaterial = [];
          }
          this.packageMaterialArr = this.copyPackageMaterialArr;

          this.getSubPackageMaterialArr();

          this.savePackageFormLoading = false;
          this.savePackageLoading = false;
        })
        .catch((res) => {
          // 点击了取消
        });
    },

    buttonType(val, itemInfo) {
      if (val === 0 && itemInfo.selectPackageMaterialId === '') {
        return 'primary';
      } else if (val === itemInfo.selectPackageMaterialId) {
        return 'primary';
      } else if (val === itemInfo.acquiescePackageMaterialId) {
        return 'danger';
      } else {
        return '';
      }
    },
    isPlain(val, itemInfo) {
      let isPlain;
      if (val === 0 && itemInfo.selectPackageMaterialId === '') {
        isPlain = false;
      } else if (val === itemInfo.selectPackageMaterialId) {
        isPlain = false;
      } else if (val === itemInfo.acquiescePackageMaterialId) {
        isPlain = true;
      } else {
        isPlain = false;
      }
      return isPlain;
    },
    acquiesceStr(val, itemInfo) {
      if (val === itemInfo.acquiescePackageMaterialId) {
        return '*' + this.$t('setting.User selection');
      } else {
        return '';
      }
    },
    returnNoticeTis(item) {
      if (item.isReturn) {
        return 'color: red;';
      }
    },
    // 大货中转
    getTransferData(keyword = false) {
      const currentKeyword = keyword ? keyword : this.scannerTest;
      if (!currentKeyword) {
        return;
      }
      if (this.transferMode !== 3) {
        this.getTransferList(currentKeyword);
      } else {
        // 处理其他事务
        this.addTransferGoodsNum(currentKeyword);
      }
    },
    // 查询调货工单
    getTransferList(keyword) {
      const params = {
        keyword: keyword
      };
      this.dataLoading = true;
      getTransferListByHW(params).then((res) => {
        this.dataLoading = false;
        if (res.error !== 0) {
          this.$errorMessage(res.message);
          return;
        }
        const { data } = res;
        if (data.length === 1 && (!data[0].labelOrder || data[0].labelOrder.status === 2)) {
          this.getTransferInfo(data[0].id);
          return;
        }
        this.transferMode = 2;
        this.transferList = deepCopy(data);
      });
    },
    getTransferInfo(id, addGoods = true) {
      this.scannerShipmentBox = [];
      this.dataLoading = true;
      getTransferInfo(id).then((res) => {
        this.dataLoading = false;
        this.transferMode = 3;
        this.transferInfo = res.data;
        this.straightGoods = res.data.straightGoods;
        this.distributionGoodsList = res.data.distributionGoods;
        if (addGoods) {
          this.addTransferGoodsNum(this.scannerTest);
        }
      });
    },
    // 确认调货
    finishTransfer() {
      const data = {
        id: this.transferInfo.id,
        goodsData: []
      };
      const flag = this.straightGoods.some((item) => {
        if (!item.rlGoodsNum) {
          item.rlGoodsNum = 0;
        }
        return item.rlGoodsNum !== item.exGoodsNum;
      });
      this.straightGoods.forEach((item) => {
        const obj = {
          id: item.id,
          rlGoodsNum: item.rlGoodsNum
        };
        data.goodsData.push(obj);
      });

      if (flag) {
        this.$warning(this.$t('transfer.实际调货数量与预计调货数量存在差异，请先与用户沟通确认'), {
          title: this.$t('transfer.确认调货？')
        })
          .then(() => {
            this.finishTransferV2(data);
          })
          .catch(() => {});
      } else {
        this.finishTransferV2(data);
      }
    },
    finishTransferV2(data) {
      this.btnLoading = true;
      finishTransfer(data).then((res) => {
        this.btnLoading = false;
        if (res.error === 0) {
          this.$successMessage(res.message);
          this.cancelOp();
        } else {
          this.$errorMessage(res.message);
        }
      });
    },
    // 扫描添加数量
    addTransferGoodsNum(currentText) {
      if (this.boxLabelData.isBox) {
        let flag = this.straightGoods.some((goods) => {
          if (goods.suitListId === this.boxLabelData.suitListId) {
            const index = this.scannerShipmentBox.findIndex((item) => item === currentText);
            if (index !== -1) {
              this.$errorMessage(this.$t('hd.该箱标已经扫描了'));
            } else {
              this.scannerShipmentBox.push(currentText);
              this.transferAddGoodsNum(goods, this.boxLabelData.goodsBoxNum);
            }
            return true;
          }
          return false;
        });
        if (flag) return;
      }

      const findGoods = this.straightGoods.some((goods) => {
        if ((goods.fromGoodsIsSystem && goods.fromSku === currentText) || goods.inventoryId === currentText) {
          let rlGoodsNum = goods.rlGoodsNum;
          if (rlGoodsNum + 1 > goods.exGoodsNum && this.ignoreShipmentSku.indexOf(currentText) === -1) {
            this.currentGoods = goods;
            this.transferGoodsNumOver(goods);
          } else {
            this.transferAddGoodsNum(goods);
          }
          return true;
        }
      });
      if (!findGoods) {
        this.switchModel();
      }
    },
    // 添加数量
    transferAddGoodsNum(goods, num = 1) {
      if (goods.rlGoodsNum === undefined) {
        goods.rlGoodsNum = 0;
      }
      goods.rlGoodsNum += num;
      const message = `${goods.goodsId}(${goods.sku})  +${num}`;
      this.$successMessage(message);
    },
    // 数量超过了
    transferGoodsNumOver(goods) {
      getTransferListByHW({
        keyword: goods.sku,
        currentId: this.transferInfo.id
      }).then((res) => {
        const { data } = res;
        this.transferList = data;
        if (data.length === 0) {
          this.goodsNumOverDialog1 = true;
        } else {
          this.selectShipmentId = data[0].id;
          this.goodsNumOverDialog2 = true;
        }
      });
    },
    // 切换模式
    switchModel() {
      let html = this.$t('hd.当前SKU不存于其他工单中，您是否需要切换硬件模式？');
      html += '<br/>';
      html += this.$t('hd.选中并切换后，当前工单仅为您做保存处理，不会直接确认工单，您还需要重新确认');
      this.$alert(html, this.$t('hd.SKU不存在于该工单中'), {
        dangerouslyUseHTMLString: true,
        // type:'warning',
        showCancelButton: true,
        cancelButtonText: this.$t('common.cancel'),
        cancelButtonClass: 'el-button--primary',
        confirmButtonText: this.$t('hd.Switch Mode'),
        confirmButtonClass: 'el-button--danger'
      })
        .then((res) => {
          //
          this.resetWorkType();
          this.cancelOp();
        })
        .catch((res) => {});
    },
    getMiddleData(keyword = false) {
      const currentKeyword = keyword ? keyword : this.scannerTest;
      if (!currentKeyword) {
        return;
      }
      if (this.middleMode !== 3) {
        this.getMiddleList(currentKeyword);
      } else {
        // 处理其他事务
        this.addMiddleGoodsNum(currentKeyword);
      }
    },
    getMiddleList(keyword) {
      const params = {
        keyword: keyword
      };
      this.dataLoading = true;
      getMiddleListByHM(params).then((res) => {
        this.dataLoading = false;
        if (res.error !== 0) {
          this.$errorMessage(res.message);
          return;
        }
        const { data } = res;
        if (data.length === 1 && (!data[0].labelOrder || data[0].labelOrder.status === 2)) {
          this.getMiddleInfo(data[0].id);
          return;
        }
        this.middleMode = 2;
        this.middleList = deepCopy(data);
      });
    },
    // 获取中转
    getMiddleInfo(id, addGoods = true) {
      this.scannerShipmentBox = [];
      this.dataLoading = true;
      getMiddleInfo(id).then((res) => {
        this.dataLoading = false;
        this.middleMode = 3;
        this.middleInfo = res.data;
        this.middleDistributionGoodsList = this.middleInfo.distributionGoods;
        this.middleStraightGoods = this.middleInfo.straightGoods;
        if (addGoods) {
          this.addMiddleGoodsNum(this.scannerTest);
        }
      });
    },
    // 扫描添加数量
    addMiddleGoodsNum(currentText) {
      if (this.boxLabelData.isBox) {
        let flag = this.middleStraightGoods.some((goods) => {
          if (goods.suitListId === this.boxLabelData.suitListId) {
            const index = this.scannerShipmentBox.findIndex((item) => item === currentText);
            if (index !== -1) {
              this.$errorMessage(this.$t('hd.该箱标已经扫描了'));
            } else {
              this.scannerShipmentBox.push(currentText);
              this.middleAddGoodsNum(goods, this.boxLabelData.goodsBoxNum);
            }
            return true;
          }
        });
        if (flag) return;
      }
      const findGoods = this.middleStraightGoods.some((goods) => {
        if ((goods.fromGoodsIsSystem && goods.sku === currentText) || goods.inventoryId === currentText) {
          let rlGoodsNum = goods.rlGoodsNum;
          if (rlGoodsNum + 1 > goods.exGoodsNum && this.ignoreShipmentSku.indexOf(currentText) === -1) {
            this.currentGoods = goods;
            this.middleGoodsNumOver(goods);
          } else {
            this.middleAddGoodsNum(goods);
          }
          return true;
        }
      });
      if (!findGoods) {
        this.switchModel();
      }
    },
    // 扫描加数量
    middleAddGoodsNum(goods, num = 1) {
      if (goods.rlGoodsNum === undefined) {
        goods.rlGoodsNum = 0;
      }
      goods.rlGoodsNum += num;
      const message = `${goods.goodsId}(${goods.sku})  +${num}`;
      this.$successMessage(message);
    },
    // 数量超过了
    middleGoodsNumOver(goods) {
      getMiddleListByHM({
        keyword: goods.sku,
        currentId: this.middleInfo.id
      }).then((res) => {
        const { data } = res;
        this.middleList = data;
        if (data.length === 0) {
          this.goodsNumOverDialog1 = true;
        } else {
          this.selectShipmentId = data[0].id;
          this.goodsNumOverDialog2 = true;
        }
      });
    },
    // 确认已拣货
    pickedMiddle() {
      let message = '';
      const flag = this.middleInfo.straightGoods.some((item) => {
        if (!item.rlGoodsNum) {
          item.rlGoodsNum = 0;
        }
        return item.rlGoodsNum !== item.exGoodsNum;
      });
      if (flag) {
        message = this.$t('middle.实际送仓数量与预计送仓数量存在差异，请先与用户沟通确认');
      }
      this.$confirm(message, {
        title: this.$t('middle.确认已拣货？')
      })
        .then((_) => {
          const data = {
            id: this.middleInfo.id,
            boxNum: this.middleInfo.boxNum,
            straightGoods: this.middleInfo.straightGoods
          };
          if (!data.boxNum) {
            this.$errorMessage(this.$t('middle.请填写打包货箱数量'));
            return;
          }
          this.btnLoading = true;
          pickedMiddleWorkOrder(data).then((res) => {
            this.btnLoading = false;
            if (res.error === 0) {
              this.$successMessage(res.message);
              this.cancelOp();
              this.resetWorkType();
            } else {
              this.$errorMessage(res.message);
            }
          });
        })
        .catch((_) => {});
    },
    // 贴标工单
    getLabelData(keyword = false) {
      const currentKeyword = keyword ? keyword : this.scannerTest;
      if (!currentKeyword) {
        return;
      }
      if (this.labelMode !== 3) {
        this.getLabelList(currentKeyword);
      } else {
        // 处理其他事务
        this.addLabelGoodsNum(currentKeyword);
      }
    },
    getLabelList(keyword) {
      const params = {
        keyword: keyword
      };
      this.dataLoading = true;
      getLabelListByHM(params).then((res) => {
        this.dataLoading = false;
        if (res.error !== 0) {
          this.$errorMessage(res.message);
          return;
        }
        const { data } = res;
        if (data.length === 1) {
          this.getLabelInfo(data[0].id);
          return;
        }
        this.labelMode = 2;
        this.labelList = deepCopy(data);
      });
    },
    getLabelInfo(id, addGoods = true) {
      this.dataLoading = true;
      getLabelOrderInfo(id).then((res) => {
        this.dataLoading = false;
        this.labelInfo = res.data;
        this.labelGoodsData = res.info.goodsData;
        this.labelMode = 3;
        if (addGoods) {
          this.addLabelGoodsNum(this.scannerTest);
        }
      });
    },
    // 设置箱标数据并且判断扫描的是不是箱标
    async setBoxLabelData() {
      this.resetBoxLabelData();
      const version = this.scannerTest.substring(0, 3);
      if (version === 'v1-') {
        const currentArr = this.scannerTest.split('-');
        this.boxLabelData.isBox = true;
        let id = Number(currentArr[1]);
        let suitListId = currentArr[3];
        if (suitListId === boxLabel.MIX) {
          this.boxLabelData.isMix = true;
          this.boxLabelData.shipmentId = id;
        } else if (suitListId === boxLabel.TB) {
          this.boxLabelData.isTB = true;
          this.boxLabelData.id = id;
        } else {
          this.boxLabelData.id = id;
          this.boxLabelData.suitListId = Number(suitListId);
          this.boxLabelData.systemLabelId = Number(currentArr[5]);
          this.boxLabelData.isSystemLabel = this.boxLabelData.systemLabelId !== 0;
        }
        this.boxLabelData.boxVersion = 'v1';
      } else {
        this.boxLabelData.isBox = false;
        this.boxLabelData.isSystemLabel = false;
        await getBoxLabelInfo(this.scannerTest).then((res) => {
          // 设置箱标对应的属性
          const { data } = res;
          this.boxLabelData.id = data.shipmentGoodsId;
          this.boxLabelData.shipmentId = data.shipmentId;
          this.boxLabelData.containerId = data.containerId;
          this.boxLabelData.boxNumber = data.iBox;
          this.boxLabelData.suitId = data.suitId;
          this.boxLabelData.suitListId = data.suitListId;
          this.boxLabelData.goodsBoxNum = data.goodsBoxNum;
          this.boxLabelData.isSystemLabel = data.isSystemLabel;
          this.boxLabelData.systemLabelId = data.systemLabelId;
          this.boxLabelData.isTB = data.isTB;
          this.boxLabelData.isMix = data.isMix;
          this.boxLabelData.isBox = data.isBox;
          this.boxLabelData.isScan = data.isScan;
          this.boxLabelData.boxVersion = data.boxVersion;
          this.boxLabelData.planId = data.planId;
          this.boxLabelData.planType = data.planType;
          this.boxLabelData.boxId = data.boxId;
        });
      }
    },
    // 把数据设置回默认值
    resetBoxLabelData() {
      this.boxLabelData.id = 0;
      this.boxLabelData.shipmentId = 0;
      this.boxLabelData.boxNumber = 0;
      this.boxLabelData.suitListId = 0;
      this.boxLabelData.suitId = 0;
      this.boxLabelData.goodsBoxNum = 0;
      this.boxLabelData.isSystemLabel = false;
      this.boxLabelData.systemLabelId = 0;
      this.boxLabelData.isTB = false;
      this.boxLabelData.isMix = false;
      this.boxLabelData.isBox = false;
      this.boxLabelData.isScan = false;
      this.boxLabelData.boxVersion = 'v1';
      this.boxLabelData.containerId = 0;
      this.boxLabelData.planId = 0;
      this.boxLabelData.planType = '';
      this.boxLabelData.boxId = '';
    },
    // 扫描添加数量
    addLabelGoodsNum(currentText) {
      let goodsList = [];
      // 扫描的是箱标
      if (this.boxLabelData.isBox) {
        const index = this.scannerShipmentBox.findIndex((item) => item === currentText);
        if (index !== -1) {
          this.$errorMessage(this.$t('hd.该箱标已经扫描了'));
          return;
        }

        this.scannerShipmentBox.push(currentText);
        goodsList = this.scanBoxLabelGoods;
        this.selectLabelGoods = goodsList;
        if (goodsList.length > 0) {
          this.goodsLabelPDFDialog = true;
          this.goodsLabelPDF.labelGoodsId = goodsList[0].id;
          this.goodsLabelPDF.num = this.boxLabelData.goodsBoxNum;
          this.goodsLabelPDF.stockType = goodsList[0].exOneStock > 0 ? 1 : 2;
          this.goodsLabelPDF.exOneStock = goodsList[0].exOneStock;
          this.goodsLabelPDF.exMiddleStock = goodsList[0].exMiddleStock;
          return;
        }
      } else {
        // 如果是sku 只能是匹配系统标
        goodsList = this.labelGoodsData.filter((goods) => {
          return (goods.fromGoodsIsSystem && (goods.fromSku === currentText || goods.systemLabelBarcode === currentText)) || goods.fromInventoryId === currentText;
        });
        if (goodsList.length > 0) {
          this.goodsLabelPDF.labelGoodsId = goodsList[0].id;
          this.goodsLabelPDF.num = 1;
          this.goodsLabelPDF.stockType = goodsList[0].exOneStock > 0 ? 1 : 2;
          this.goodsLabelPDF.exOneStock = goodsList[0].exOneStock;
          this.goodsLabelPDF.exMiddleStock = goodsList[0].exMiddleStock;
          if (goodsList.length > 1 || (goodsList[0].exOneStock > 0 && goodsList[0].exMiddleStock > 0)) {
            this.goodsLabelPDFDialog = true;
          } else {
            // 直接打印箱标
            this.exportLabelPdf();
          }
        }
      }
      this.selectLabelGoods = goodsList;

      if (goodsList.length === 0) {
        this.switchModel();
      }
    },
    // 导出箱标
    exportLabelPdf() {
      const stockType = this.goodsLabelPDF.stockType;
      const params = {
        id: this.goodsLabelPDF.labelGoodsId,
        num: this.goodsLabelPDF.num
      };
      this.btnLoading = true;
      exportLabelGoodsLabelPdf(params).then((res) => {
        this.goodsLabelPDFDialog = false;
        this.btnLoading = false;
        this.sendPrint(res.data);
        const labelGoods = this.labelGoodsData.find((item) => item.id === params.id);
        if (labelGoods) {
          if (stockType === 1) {
            labelGoods.rlOneStock += params.num;
          } else {
            labelGoods.rlMiddleStock += params.num;
          }
          labelGoods.rlGoodsNum += params.num;
          this.$successMessage(`${labelGoods.toGoodsId}(${labelGoods.toSku}) + ${params.num}`);
          this.saveLabelGoodsNum(labelGoods);
        }
      });
    },
    checkLabelGoodsNum() {
      this.labelGoodsData.forEach((item) => {
        item.rlGoodsNum = item.rlOneStock + item.rlMiddleStock;
      });
      const flag = this.labelGoodsData.some((item) => {
        return item.rlGoodsNum !== item.exGoodsNum;
      });
      if (flag) {
        this.$warning(this.$t('labelOrder.实际贴标数据与预计贴标数量有差异，请先与客户沟通确认'), {
          title: this.$t('labelOrder.确认贴标？')
        })
          .then(() => {
            this.finishLabelOrder();
          })
          .catch(() => {});
      } else {
        this.finishLabelOrder();
      }
    },
    // 确认已贴标
    finishLabelOrder() {
      this.labelGoodsData.forEach((item) => {
        item.rlGoodsNum = item.rlOneStock + item.rlMiddleStock;
      });
      const data = {
        id: this.labelInfo.id,
        goodsData: this.labelGoodsData
      };
      this.btnLoading = true;
      finishLabelOrder(data).then((res) => {
        this.btnLoading = false;
        if (res.error === 0) {
          this.$successMessage(res.message);

          let type = '';
          let id = 0;
          if (this.labelInfo.shipment) {
            type = workTypeMap.tallying;
            id = this.labelInfo.shipment.id;
          } else if (this.labelInfo.middle) {
            type = workTypeMap.middle;
            id = this.labelInfo.middle.id;
          } else if (this.labelInfo.transfer) {
            type = workTypeMap.transfer;
            id = this.labelInfo.transfer.id;
          }
          this.cancelOp();
          this.resetWorkType();
          if (type) {
            this.currentWorkType = type;
            switch (type) {
              case workTypeMap.tallying:
                this.getShipmentInfo(id, false);
                break;
              case workTypeMap.middle:
                this.getMiddleInfo(id, false);
                break;
              case workTypeMap.transfer:
                this.getTransferInfo(id, false);
                break;
            }
          }
        } else {
          this.$errorMessage(res.message);
        }
      });
    },
    // 是否切换贴标工单
    isSwitchLabelModel(labelOrderId) {
      let html = this.$t('hd.切换贴标工单提示语');
      this.$confirm(html, this.$t('hd.当前工单存在待贴标工单'), {
        dangerouslyUseHTMLString: true,
        confirmButtonText: this.$t('labelOrder.贴标工单')
      })
        .then((_) => {
          this.cancelOp();
          this.currentWorkType = workTypeMap.label;
          this.getLabelInfo(labelOrderId, false);
          this.labelMode = 3;
        })
        .catch((_) => {});
    },
    // 子组件请求 打印打印pdf
    printPDF(printData) {
      if (!this.currentPrinter) {
        this.$errorMessage('暂无打印机');
        return;
      }

      const data = {
        pdfData: printData,
        printerName: this.currentPrinter.name
      };
      this.printerPDFType = 2;
      this.printerTestLoading = true;
      this.sendSocket('print', data);
    },
    // 跳转至库位列表
    jumpInventoryLocationList() {
      this.$router.push({
        name: 'inventoryLocationList'
      });
    },
    logisticsPrintShipping() {
      this.logisticsLoading = true;
      this.getPickingData();
    },
    closeLogisticsDialog() {
      this.logisticsDialog = false;
      this.getDefaultLogisticsType = '';
    }
  },
  components: {
    ContainerInfoView,
    GunModelSet,
    LabelOrderInfoView,
    MiddleInfoView,
    TransferInfoView,
    ToolTipShipmentBox,
    Scanner,
    ShipmentInfoView,
    HardwarePrintSkuInfo,
    ShipmentInfoImg,
  },
  destroyed() {
    if (this.socket && this.socket.connected) {
      this.socket.close();
    }
    if (this.printerInterval) {
      clearInterval(this.printerInterval);
    }
  }
};
</script>

<style>
.scan-dialog {
  .el-dialog {
    background-color: #fdf6ec;
  }
}
.my-custom-dialog .el-dialog__body {
  background-color: rgba(253, 246, 236, 1);
}
.my-custom-dialog .el-dialog__header {
  background-color: rgba(253, 246, 236, 1);
}
.my-custom-dialog .el-dialog__footer {
  background-color: rgba(253, 246, 236, 1);
}
</style>
<style scoped lang="scss">
.wrap {
  padding: 30px 30px 85px;

  .header {
    display: block;
    .header-title {
      font-weight: bold;
      font-size: 24px;
    }
  }
  .content {
    padding: 20px 0 0;
    .header-tips {
      font-size: 14px;
      //font-weight: bold;
      color: #ff0000;
      margin-top: 10px;
      padding: 10px;
      width: 600px;
      border: 1px dotted #ff0000;
    }
    .picking-goods-tips {
      font-size: 14px;
      //font-weight: bold;
      color: #409eff;
      margin-top: 10px;
      padding: 10px;
      width: 400px;
      border: 1px dotted #409eff;
      margin-left: 50px;
    }
    .scanner-text {
      margin-top: 20px;
    }
    .scanner-body {
      margin-top: 30px;
    }
  }
}
.wait-color {
  color: #409eff;
}
.success-color {
  color: #67c23a;
}
.error-color {
  color: #f56c6c;
}

.order-card {
  width: 800px;
  .order-body {
    display: flex;
  }
  .left {
    width: 150px;
    text-align: center;
    vertical-align: middle;
  }
  .right {
    width: 60%;
    .order-card-label {
      font-size: 14px;
    }
    .order-card-text {
      font-size: 14px;
    }
  }
}

.remark-shipping {
  color: #409eff;
}
.remark-delivery {
  color: #ff0000;
  font-weight: bold;
}

.order-package {
  margin-top: 10px;
  display: flex;
}
.printer-content {
  margin-top: 10px;
  display: flex;
}
.printer-content2 {
  margin-top: 10px;
}
.app-check-tips {
  font-size: 14px;
  //font-weight: bold;
  color: #ff0000;
  margin-bottom: 20px;
  padding: 10px;
  width: 500px;
  border: 1px dotted #ff0000;
}
.gun-model-tips {
  font-size: 12px;
  color: #aaaaaa;
}
.order-content {
  display: flex;
  .left {
    margin-right: 20px;
  }
}
.listing-font {
  color: #333333;
  font-weight: bold;
}
.attr-font {
  color: #f5222d;
  font-size: 14px;
  font-weight: bold;
}
.title-font {
  font-size: 14px;
  color: #aaaaaa;
}
.scanner-body {
  .order-item {
    position: relative;

    .order-alert {
      position: absolute;
      top: 100px;
      left: 300px;
      width: 800px;
      .font-normal {
        color: #333333;
      }
    }
  }
}
.work-type-select {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  .work-type-box {
    width: 150px;
    margin-right: 30px;
    .work-type-card {
      border: 1px solid #cccccc;
      width: 150px;
      height: 150px;
      padding: 10px;
      cursor: pointer;
      .title {
        font-weight: bold;
        margin-bottom: 5px;
      }
      .work-img {
        text-align: center;
        img {
          width: 100px;
        }
      }
    }
    .work-type-title {
      margin-top: 5px;
      text-align: center;
      font-weight: bold;
    }
    .work-type-card:hover {
      background-color: #f6ffed;
    }
  }
}
.work-content {
  margin-top: 30px;
  .tips-text {
    color: #aaaaaa;
  }
}
.card-box {
  display: flex;
  .order-card-1 {
    width: 1000px;
    height: 200px;
    .order-header-title {
      color: #ff0000;
      font-weight: bold;
      margin-bottom: 10px;
      margin-top: -5px;
    }
  }
  .order-card-2 {
    width: 800px;
    height: 170px;
    .order-header-title {
      color: #ff0000;
      font-weight: bold;
      margin-bottom: 10px;
      margin-top: -5px;
    }
  }
  .order-weight-card {
    width: 500px;
    height: 170px;
    .order-weight-card-content {
      display: flex;
      flex-direction: column;
      height: 120px;
      justify-content: space-around;
    }
  }
  .order-return-card {
    width: 300px;
    height: 200px;
    background-color: #ffffed;
    .return-header-title {
      color: #ff0000;
      font-weight: bold;
      margin-bottom: 10px;
      margin-top: -5px;
    }
    .return-header-text {
      font-weight: bold;
      font-size: 20px;
      margin-top: 25px;
      margin-bottom: 25px;
    }
    .return-btn {
      margin-bottom: 10px;
    }
    .return-op-tips {
      font-size: 24px;
      font-weight: bold;
      color: #ff0000;
    }
  }
}
.return-order-list {
  margin-top: 30px;
  .return-order-item {
    display: flex;
    .left {
      margin-right: 30px;
    }
    .right {
      .goods-info-card {
        width: 890px;
        height: 190px;
        .goods-info-card-content {
          display: flex;
          height: 150px;
          flex-direction: column;
          justify-content: space-around;
          font-size: 16px;
          .goods-listing {
            font-weight: bold;
          }
          .goods-title {
            color: #aaaaaa;
          }
          .goods-SKU-info {
            color: #333333;
          }
          .goods-attr {
            color: #ff0000;
            font-weight: bold;
          }
          .return-input {
            font-size: 14px;
          }
        }
      }
    }
  }
}
.footer {
  position: fixed;
  bottom: 0;
  height: 55px;
  padding-left: 30px;
  padding-top: 10px;
  border-top: 1px solid #e6ebf5;
  background-color: #ffffff;
  z-index: 2000;
  width: calc(100% + 30px);
  margin-left: -30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.font-orange {
  color: #e6a23c;
}
.mode-box {
  margin-top: 30px;
  .mode-title {
    margin-bottom: 10px;
  }
}
</style>
<style scoped lang="scss">
.wrap{
  padding: 10px 30px 80px;
  .content{
    .header-card{
      position: relative;
      font-size: 14px;
      background-color: rgba(242, 242, 242, 1);
      p{
        margin: 10px 0;
        padding: 0;
      }
      .font-bold{
        font-weight: bold;
      }
      .button{
        position: absolute;
        display: flex;
        flex-direction: column;
        right: 20px;
        top: 30px;
      }
    }
    .detail{
      margin-top: 20px;
      .table-header{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
        .left{
          .table-title{
            font-size: 18px;
            font-weight: 500;
          }
        }

      }
      .logistics-box{
        padding: 20px 30px 0;
        border: 1px solid #cccccc;
        border-radius: 5px;
        .logistics-item{
          margin-bottom: 20px;
          font-size: 15px;
          font-weight: 350;
          .time{
            color: #AAAAAA;
          }
        }
        position: relative;
        .gf-btn{
          position: absolute;
          right: 20px;
          top: 20px;
        }
        .show-limit{
          position: absolute;
          right: 20px;
          bottom: 10px;
        }
      }
    }
  }
  .season-title{
    font-size: 18px;
    font-weight: 500;
  }
}

</style>

